req.body 在服务器发送数据时为空,在本地工作
req.body is empty when sending data in server, in local works
我正在尝试将数据发送到 index.js
,在本地主机上它工作正常,但是当我部署到我的服务器时它不工作。我看到问题似乎很相似:
here。但它对我不起作用
client.js
:
发送数据到 index.js /subscribeA
await fetch("https://example.com:30000/subscribeA", {
method: "post",
body: JSON.stringify({ dataSubscribe: subscription, dataNotif: dataNotif}),
headers: {
"Content-Type": "application/json"
},
mode : 'no-cors'
});
console.log("Push Sent...");
}
然后在 index.js
中:
var express = require('express');
const port = process.env.PORT || 30000;
const app = express();
const http = require('http');
const https = require('https');
const fs = require('fs');
var server = http.createServer(app);
const privateKey = fs.readFileSync('/etc/letsencrypt/live/example.com/privkey.pem', 'utf8');
const certificate = fs.readFileSync('/etc/letsencrypt/live/example.com/cert.pem', 'utf8');
const credintials = { key: privateKey, cert: certificate };
server = https.createServer(credintials, app);
server.listen(port, () => console.log(`Server started on port ${port}`));
const io = require("socket.io")(server, {
// allowEIO3 = true,
cors: {
credentials:true,
origin: '*',
methods: ["GET", "POST"]
}
})
const webpush = require("web-push");
const bodyParser = require("body-parser");
const path = require("path");
// Set static path
app.use(express.static(path.join(__dirname)));
app.use(bodyParser.json());
const publicVapidKey =
"BJthRQ5maDga7OSXsPC1ftGw-n16F7zQBEN7EUD6XxcfTTvrLGWSIG7y_JxiWtVlCFua0S8MTB5rPziBqNx1qIo";
const privateVapidKey = "3KsvdasAdSoCdsd0dIG_o9B0Ozvl1XDwI63JRKNIWBM";
webpush.setVapidDetails(
"mailto:test@test.com",
publicVapidKey,
privateVapidKey
);
// Subscribe Route
app.post("/subscribeA", (req, res) => {
console.log(req.body);
// Get pushSubscription object
// console.log(req.body.dataSubscribe);
const subscription = req.body.dataSubscribe;
const dataNotif = req.body.dataNotif;
if(dataNotif == null){
console.log('kosong rek');
}else{
console.log(dataNotif);
}
// Send 201 - resource created
res.status(201).json({});
// Create payload
const payload = JSON.stringify({ head: "yobro", content: "kontennnya bro"});
// Pass object into sendNotification
webpush
.sendNotification(subscription, payload)
.catch(err => console.error(err));
});
io.on('connection', function (socket) {
socket.on('notifikasi', function (data) {
io.sockets.emit('notifikasi', {
isi_notif: data.isi_notif});
});
});
请求载荷
{dataSubscribe: {,…}, dataNotif: {head: "@username", content: "yo"}}
dataNotif: {head: "@username", content: "yo"}
dataSubscribe: {,…}
因此,它正在正确发送数据,但是在 index.js
中,当我使用 console.log(req.body)
它时 return 空数组 {}
.
在您的 fetch()
中使用 no-cors
意味着 content-type 只能是以下之一:"application/x-www-form-urlencoded"
、"multipart/form-data"
或 "text/plain"
(更多解释here)。因此,您的 "application/json"
不被允许,因此服务器无法正确 read/parse body.
只允许简单的 headers 与 no-cors
一起使用,您可以阅读有关 here.
的内容
您必须停止在抓取中使用 no-cors
才能使用 JSON 或更改内容以使用允许的 content-type 之一。
仅供参考,在这种情况下,注销传入请求的重要预期方面通常会有所帮助。在这种情况下,您可以记录 content-type
并查看您得到了什么。您还可以在 Chrome 调试器的网络选项卡中查看从浏览器发送的请求。两者都可能会向您展示与 content-type.
相关的内容
我正在尝试将数据发送到 index.js
,在本地主机上它工作正常,但是当我部署到我的服务器时它不工作。我看到问题似乎很相似:
here。但它对我不起作用
client.js
:
发送数据到 index.js /subscribeA
await fetch("https://example.com:30000/subscribeA", {
method: "post",
body: JSON.stringify({ dataSubscribe: subscription, dataNotif: dataNotif}),
headers: {
"Content-Type": "application/json"
},
mode : 'no-cors'
});
console.log("Push Sent...");
}
然后在 index.js
中:
var express = require('express');
const port = process.env.PORT || 30000;
const app = express();
const http = require('http');
const https = require('https');
const fs = require('fs');
var server = http.createServer(app);
const privateKey = fs.readFileSync('/etc/letsencrypt/live/example.com/privkey.pem', 'utf8');
const certificate = fs.readFileSync('/etc/letsencrypt/live/example.com/cert.pem', 'utf8');
const credintials = { key: privateKey, cert: certificate };
server = https.createServer(credintials, app);
server.listen(port, () => console.log(`Server started on port ${port}`));
const io = require("socket.io")(server, {
// allowEIO3 = true,
cors: {
credentials:true,
origin: '*',
methods: ["GET", "POST"]
}
})
const webpush = require("web-push");
const bodyParser = require("body-parser");
const path = require("path");
// Set static path
app.use(express.static(path.join(__dirname)));
app.use(bodyParser.json());
const publicVapidKey =
"BJthRQ5maDga7OSXsPC1ftGw-n16F7zQBEN7EUD6XxcfTTvrLGWSIG7y_JxiWtVlCFua0S8MTB5rPziBqNx1qIo";
const privateVapidKey = "3KsvdasAdSoCdsd0dIG_o9B0Ozvl1XDwI63JRKNIWBM";
webpush.setVapidDetails(
"mailto:test@test.com",
publicVapidKey,
privateVapidKey
);
// Subscribe Route
app.post("/subscribeA", (req, res) => {
console.log(req.body);
// Get pushSubscription object
// console.log(req.body.dataSubscribe);
const subscription = req.body.dataSubscribe;
const dataNotif = req.body.dataNotif;
if(dataNotif == null){
console.log('kosong rek');
}else{
console.log(dataNotif);
}
// Send 201 - resource created
res.status(201).json({});
// Create payload
const payload = JSON.stringify({ head: "yobro", content: "kontennnya bro"});
// Pass object into sendNotification
webpush
.sendNotification(subscription, payload)
.catch(err => console.error(err));
});
io.on('connection', function (socket) {
socket.on('notifikasi', function (data) {
io.sockets.emit('notifikasi', {
isi_notif: data.isi_notif});
});
});
请求载荷
{dataSubscribe: {,…}, dataNotif: {head: "@username", content: "yo"}}
dataNotif: {head: "@username", content: "yo"}
dataSubscribe: {,…}
因此,它正在正确发送数据,但是在 index.js
中,当我使用 console.log(req.body)
它时 return 空数组 {}
.
在您的 fetch()
中使用 no-cors
意味着 content-type 只能是以下之一:"application/x-www-form-urlencoded"
、"multipart/form-data"
或 "text/plain"
(更多解释here)。因此,您的 "application/json"
不被允许,因此服务器无法正确 read/parse body.
只允许简单的 headers 与 no-cors
一起使用,您可以阅读有关 here.
您必须停止在抓取中使用 no-cors
才能使用 JSON 或更改内容以使用允许的 content-type 之一。
仅供参考,在这种情况下,注销传入请求的重要预期方面通常会有所帮助。在这种情况下,您可以记录 content-type
并查看您得到了什么。您还可以在 Chrome 调试器的网络选项卡中查看从浏览器发送的请求。两者都可能会向您展示与 content-type.