req.body пуст, когда отправляю запрос через fetch. Почему? Как исправить?
//Front:
fetch("http://127.0.0.1:3000/test", {
method: "post",
headers: {
"Content-type": "application/json; charset=UTF-8",
},
body: JSON.stringify("heeey")
})
.then((data)=>{
return data.json();
})
.then((res)=>{
console.log(res);
})
.catch((err)=>{
console.log('Request failed ', err );
});
//Back:
const express = require('express')
const bodyParser = require("body-parser");
const app = express();
const urlencodedParser = bodyParser.urlencoded({extended: false});
const port = 3000
app.use((req, res, next)=>{
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type");
if(req.method == "OPTIONS"){
return res.status(200).send('ok');
}
next();
})
app.post('/test', urlencodedParser, (req, res) => {
console.log(req.body)
res.status(200).send({
t: 1,
d: 2,
test: req.body
})
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));```
Ответы (1 шт):
Автор решения: Tangerine
→ Ссылка
Исправил bodyParser.urlencoded({extended: false}); на bodyParser.json(); Все заработало, всем спасибо с: