Version: express@4.16.4 , body-parser@1.18.3
Tested with nodejs setup on AWS EC2, and a html webpage run directly on local machine. I notice that there is an inconsistent behavior in the calling sequence of middleware/router. In following html, the GET request is ok returning json {from:'nodejs'}
. However, POST request jumps directly to method Invalid URL
.
More test scenarios:
- Entirely remove the second
app.use
both GET and POST requests are ok returning json{from:'nodejs'}
, and POST requestreq.body
output the correct data{from:'html'}
- Removing
xhr.setRequestHeader("Content-Type", "application/json");
both GET and POST requests are ok returning json{from:'nodejs'}
, butreq.body
is blank which is expected
html code:
<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="get()">GET</button>
<button type="button" onclick="post()">POST</button>
<p id="output"></p>
<script>
function get() {
var xhr = new XMLHttpRequest();
xhr.open("GET", 'http://54.169.54.221:8000/get', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log("Server Responded:" + JSON.stringify(json));
document.getElementById("output").innerHTML = JSON.stringify(json);
}
};
xhr.send();
}
function post() {
var json = '{"from":"html"}';
var xhr = new XMLHttpRequest();
xhr.open("POST", 'http://54.169.54.221:8000/post', true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log("Server Responded:" + JSON.stringify(json));
document.getElementById("output").innerHTML = JSON.stringify(json);
}
};
xhr.send(json);
}
</script>
</body>
</html>
Server code:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(function(req, res, next) {
console.log( 'global pre-process middleware invoked' );
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'content-type');
next();
});
app.get('/get', function (req, res, next) {
try {
var json = {from:'nodejs'};
console.log( JSON.stringify(json,null,' ') );
res.end( JSON.stringify(json,null,' ') );
} catch (e) {
next(e);
}
});
app.post('/post', function (req, res, next) {
try {
console.log(JSON.stringify(req.body));
var json = {from:'nodejs'};
console.log( JSON.stringify(json,null,' ') );
res.end( JSON.stringify(json,null,' ') );
} catch (e) {
next(e);
}
});
app.use(function(req, res, next) {
console.log('Invalid URL');
});
var server = app.listen(8000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Listening at http://%s:%s', host, port);
});