'Node and Express simple POST - 400 Bad Request
Surely I'm doing something stupid, because this should be the easiest thing in the world.
All I'm trying to do is perform a POST in an Express route.
My app.js:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
My index.js route:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('index', {title: 'Express'});
});
router.post("/test", function(req, res) {
console.log("Hello...anyone!?");
res.end();
});
module.exports = router;
The GET works fine. I can pull http:/localhost:3000 right up in a browser.
When I fire a POST against http:/localhost:3000/test it results in a 400 Bad Gateway.
Solution 1:[1]
In the end, this had nothing to do with Node or the code posted. I rebooted my PC and the issue went away. I can't find anything that explains it.
Solution 2:[2]
In case anyone finds this helpful, I ran into the same issue and the culprit turned out to be missing headers. I knew I needed the "Content-Type": "application/json"
header, which I already had in place, but I didn't know that I was missing two other headers.
The solution for me was also adding the "Content-Length"
and "Host"
headers in Postman.
I see some others have questioned the need for the "Content-Length"
header, but in my case, the minimum three needed were "Content-Type"
, "Content-Length"
, and "Host"
or it would always fail.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tsar Bomba |
Solution 2 |