Node js express
I got {}, which is empty, when I want req.body
I've tried so many methods but they seem like don't work for my code.
I use fetch to post it.
index.js
const express = require('express');
const PORT = process.env.PORT || 3000;
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/test_module.html');
});
app.post('/register', (req, res) => {
console.log(req.body);
});
app.listen(PORT, () => {
console.log(`http://localhost:${PORT}`);
});
script in html
var json = {
username: username.value,
password: password.value
};
console.log(json);
// {username: 'a', password: 'b'}
fetch('http://localhost:3000/register', {
method: 'POST',
body: json,
}).then(function(res) {
return res.json();
}).then(function(res) {
console.log(res);
});
I got output:
http://localhost:3000
{}