I'm trying to send a JSON object to an express server. This is my code for the client:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Express demo</title>
</head>
<body>
<button onclick="sendUrlEncoded()">Send an application/x-www-form-urlencoded POST request</button>
<button onclick="sendJson()">Send an application/json POST request</button>
<div id="response"></div>
<script>
function sendUrlEncoded() {
var data = "text=stuff";
var http = new XMLHttpRequest();
http.open("POST", "http://127.0.0.1");
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(data);
}
function sendJson() {
var data = {text:"stuff"};
var http = new XMLHttpRequest();
http.open("POST", "http://127.0.0.1");
http.setRequestHeader("Content-Type", "application/json");
http.send(JSON.stringify(data));
}
</script>
</body>
</html>
And this is the server:
var express = require("express");
var path = require("path");
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(function(req, res, next) {
console.log("Received request");
console.log(req.headers);
console.log(req.body);
next();
});
app.get("/", function(req, res) {
console.log("GET request");
res.sendFile(path.join(__dirname + "/index.html"));
});
app.post("*", function(req, res) {
console.log("Received post request");
res.status=200;
});
var server = app.listen(3001, function() {console.log("Listening on port 3001")});
sendJson() was formerly "sendPost()" in the original version of this question. When the client sends a GET request or an XMLHttpRequest, the server always receives it. If it's a GET request or sent via sendUrlEncoded(), it contains the data in the body and calls the app.get() function successfully. However, with sendJson(), the server only gets the request in the general message handler. It doesn't call app.get(), and the request's body is {}. In addition, the header is not quite what I expect:
{
host: 'xx.xxx.xxx.xxx:3001',
connection: 'keep-alive',
accept: '*/*',
'access-control-request-method': 'POST',
'access-control-request-headers': 'content-type',
origin: 'http://192.168.0.102:3001',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
'sec-fetch-mode': 'cors',
referer: 'http://192.168.0.102:3001/',
'accept-encoding': 'gzip, deflate',
'accept-language': 'en-US,en;q=0.9'
}
Note: I replaced the real IP address with xx.xxx.xxx.xxx above. If you can help, I really appreciate it!
