My goal is to transmit a JSON object to an express server. Below is the code I have written for the client side:
<!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>
Here is the code for the server side implementation:
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")});
In a previous version of my code, the function sendJson() was named as "sendPost()". Upon testing, it was observed that when a GET request or XMLHttpRequest is sent from the client, the server always receives it successfully. However, there are some issues with the way the server handles different types of requests. When using sendUrlEncoded() or sending a GET request, the data is received by the server in the body and the app.get() function is called correctly. But, with sendJson(), the server only picks up the request in the general message handler. The app.get() function is not triggered and the request body shows {}. Furthermore, the header received is not as expected:
{
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: For privacy reasons, I have replaced the actual IP address with xx.xxx.xxx.xxx. Any assistance would be greatly appreciated!