I tried to do post request to other localhost server(because in project I'm using webpack and I don't know how to manage default webpack server).
This is my post request file.
btn_bag[0].addEventListener('click', (e) => {
e.preventDefault(),
fetch('http://localhost:3000/get', {
method:'POST',
headers: {
'Content-Type':'application/json;charset=utf-8'
},
body: JSON.stringify(order_pizza)
})
.then(console.log(order_pizza))
})
This is my server, when I click on button, console in server logged {}, when "order_pizza"(variable which I post) is not empty. What is the problem, help to find solution, please.
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const fs = require('fs');
const cors = require('cors');
const urlencodedParser = bodyParser.urlencoded({extended: false})
app.get('/', (req, res) => {
res.send('hello')
})
app.use(cors({
allowedOrigins: [
'http://localhost:9000'
]
}));
app.get('/get', (req,res) => {
console.log(req.body)
res.send('get')})
app.post('/get',urlencodedParser, (req,res) => {
console.log(req.body)})
app.listen(3000)
In your front-end, do not stringify the body, send it as an object like below. Change also the targetted end-point to /post
btn_bag[0].addEventListener('click', (e) => {
e.preventDefault(),
fetch('http://localhost:3000/post', {
method:'POST',
headers: {
'Content-Type':'application/json;charset=utf-8'
},
body: {order_pizza}
})
.then(console.log(order_pizza))
})
In your server, change the end-point URL to /post
so that it makes sense. And access the request body like below. And you do not need the urlencodedParser
on this end-point
app.post('/post', (req,res) => {
console.log(req.body)})
})
Also apply the body-parser to your express app like below
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
try this
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
you don't have to pass urlencodedParser in app.post api call, i hope it helps
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.