I have a server running Express, and a client written in JS. Using the following code on the client:
document.getElementById("continue").addEventListener("click", function() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if(username != "" && password != "") {
const data = {
username, password
};
console.log(JSON.stringify(data));
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
};
fetch(urllogin, options).then(response => {
console.log(response.body);
});
}
And the following code on the server:
let port = 9000;
var express = require("express");
var fs = require("fs");
var https = require("https");
var app = express();
app.use(express.json())
app.use((req, res, next) => {
res.append('Access-Control-Allow-Origin', ['*']);
res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.append('Access-Control-Allow-Headers', 'Content-Type');
next();
});
app.post("/login", (req, res) => {
console.log(req.body);
response = {
body:'hello'
};
res.json(JSON.stringify(response));
});
https
.createServer(
{
key: fs.readFileSync("server.key"),
cert: fs.readFileSync("server.cert"),
},
app
)
.listen(port, function () {
console.log(`Example app listening on port ${port}! Go to https://localhost:${port}/`);
});
I successfully receive the JSON object on the server, but on the client, I get:
{"username":"ok","password":"m"} script.js:20:21
ReadableStream { locked: false }
locked: false
<prototype>: ReadableStreamPrototype { cancel: cancel(), getReader: getReader(), pipeTo: pipeTo(), … }
script.js:29:25
Logged in the console (posted just a part of it).
Why does this happen, and how can I send data as a response to a POST request? Thank you!