【问题标题】:Request Body Empty with Express Body Parser使用 Express Body Parser 请求 Body Empty
【发布时间】:2016-10-30 02:26:15
【问题描述】:

我目前正在使用 body-parser 尝试接收 POST 数据,但我的请求正文返回一个空对象。我似乎无法弄清楚问题是什么。有谁知道我的代码可能有什么问题?

这是我的代码:

// Script intialized by Gulp
const path = require('path')
const bodyParser = require('body-parser')
const express = require('express')
const app = express()

// Import registration and login functionality from database.js
const database = require('./database')

// Configuration
let jsonParser = bodyParser.json()
app.use(jsonParser)
app.use(express.static(path.join(__dirname, '../../docs')))
app.use(express.static(path.join(__dirname, '../../src')))

app.set('port', process.env.PORT || 8080);
app.set('view engine', 'pug')
app.set('views', 'src/pages')

app.listen(app.get('port'))
console.log('Listening on port: ' + app.get('port'))

// Routing
app.get('/', function(req, res) {
    console.log('Welcome!')
    res.render('index');
})

app.get('/login', function(req, res) {
    console.log('Uhh, it looks like something went wrong here')
    res.end()
})

// Link with database.js to link username and password attributes
app.post('/login', jsonParser, function(req, res) {
    console.log(req)
    console.log(req.body)
    //database.login('ThisIsATestAccountBoi', 'TestPassword')
    //console.log('Username: ' + username + '\n' + 'Password: ' + password)
    res.end()
})

【问题讨论】:

  • 代码看起来不错,你是如何发布数据的?
  • @adeneo 我使用 DOM 的 .submit() 方法提交表单数据。
  • 好吧,您希望 JSON 作为唯一的数据,因为您在路由中直接使用了 jsonParser,所以如果您以 x-www-url-form-urlencoded 提交常规表单,显然不是只发送 JSON,是吗
  • @adeneo 我实际上使用了 enctype='application/json' 来设置数据,因此实际上不必如此。这只是默认设置。感谢您的建议:P
  • 你的意思是它不必是什么?你有一个类似app.post('/login', jsonParser, function(req, res) { 的路由,其中​​jsonParser 是解析JSON 请求对象并填充req.body 的中间件,如果发送的数据不是纯JSON,则解析器失败,req.body 为空?

标签: javascript node.js http express


【解决方案1】:

看到这个答案:Node.js server: get body from POST request

看起来他们缺少 Content-Type 标头。发送带有 Content-Type = application/json

标头的请求

【讨论】:

  • 不,我认为这不是问题所在。我使用 res.setHeader() 和适当的参数,它仍然返回一个空对象。不过我会继续寻找!
  • 不在服务器代码中。在您发送的请求中设置标头(来自您使用的任何工具,例如:邮递员)
【解决方案2】:

解决了我的问题。这是我的翡翠标签的问题。我将其标记为标签的方式使我的表单自行关闭,而其中没有任何组件。给您带来的不便深表歉意!

【讨论】:

    猜你喜欢
    • 2016-07-25
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多