简体   繁体   中英

Request Body Empty with Express Body Parser

I'm currently using body-parser to try and receive POST data but my request body returns an empty object. I can't seem to figure out what the issue is. Does anyone know what the issue with my code might be?

Here's my code:

// 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()
})

See this answer: Node.js server: get body from POST request

Looks like they were missing the Content-Type header. Send the request with the header Content-Type = application/json

Figured out my issue. It was an issue with my Jade tabbing. The way I had it tabbed made it so that my form closed on itself without having any components inside of it. Sorry for the inconvenience!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM