我在尝试可以在网上找到的所有解决方案,但没有运气之后,便提出了这个问题。
我正在通过chrome扩展程序向我的localhost Express服务器发出发布请求,如下所示:
await fetch(`http://127.0.0.1:3000/get-data`, {
'method': 'POST',
'content-type': 'application/json',
'body': JSON.stringify({ data: some_data_here })
}).then(response => response.json()).then(resp => {
console.log(resp)
})
这是我的快递代码
const express = require('express')
const path = require('path')
const bodyParser = require('body-parser')
const app = express()
app.use(cors({ origin: '*' }));
var jsonParser = bodyParser.json()
app.post('/get-data', jsonParser, (req, res) => {
console.log(req)
console.log('Got body:', req.body);
//some code runs here that interacts with the data and returns some data back to the chrome extension thats making the request (data => changed_data)
res.setHeader('Content-Type', 'application/json')
res.send(changed_data)
})
const PORT = process.env.PORT || 3000
app.listen(PORT, () => console.log('running'))
[当我发出请求时,获得的主体控制台将记录一个空数组,如下所示:得到了正文:{}
我做错什么了吗?我尝试了在该问题上可以找到的所有解决方案,但到目前为止,没有任何解决方案对我有用。
================================================
const express = require('express')
const path = require('path')
const bodyParser = require('body-parser')
const app = express()
const cors = require('cors')
app.use(cors({ origin: '*' }));
var jsonParser = bodyParser.json()
app.post('/get-data', jsonParser, function (req, res) {
console.log(req)
console.log('Got body:', req.body);
//some code runs here that interacts with the data and returns some data back to the chrome extension thats making the request (data => changed_data)
var changed_data = {"status":true}
res.setHeader('Content-Type', 'application/json')
res.send(changed_data)
})
const PORT = process.env.PORT || 3000
app.listen(PORT, () => console.log('running'))