1

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
{}
Phil
  • 157,677
  • 23
  • 242
  • 245
  • 4
    Does this answer your question? [Fetch: POST JSON data](https://stackoverflow.com/questions/29775797/fetch-post-json-data). _TL;DR_ you need to stringify the JSON data and add the appropriate content-type header... `headers: { 'content-type': 'application/json' }, body: JSON.stringify(json)` – Phil Jul 24 '23 at 01:54
  • try res.json(); catch res.text(); – Ronnie Royston Jul 24 '23 at 02:00
  • @RonnieRoyston handling a non-JSON response is not the problem OP is trying to solve here – Phil Jul 24 '23 at 02:01
  • 3
    Note that your `json` is not JSON, but a JavaScript object. Meanwhile, the `body` parameter to `fetch` can be "a `Blob`, an `ArrayBuffer`, a `TypedArray`, a `DataView`, a `FormData`, a `URLSearchParams`, string object or literal, or a `ReadableStream` object" (per [MDN](https://developer.mozilla.org/en-US/docs/Web/API/fetch#body)); your `json` is none of these. – Amadan Jul 24 '23 at 02:05

0 Answers0