【问题标题】:req.body is empty when sending data in server, in local works在本地工作中,在服务器中发送数据时,req.body 为空
【发布时间】:2021-09-25 02:55:20
【问题描述】:

我正在尝试将数据发送到index.js,在 localhost 中它可以正常工作,但是当我部署到我的服务器时它无法正常工作。我看到问题似乎相似: 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) 时,它返回空数组{}

【问题讨论】:

    标签: node.js express body-parser


    【解决方案1】:

    fetch() 中使用no-cors 意味着内容类型只能是以下之一:"application/x-www-form-urlencoded""multipart/form-data""text/plain"(更多解释here)。因此,您的 "application/json" 是不允许的,因此服务器无法正确读取/解析正文。

    no-cors 只允许使用简单的标头,您可以阅读有关here 的信息。

    您必须停止使用 no-cors 进行提取以使用 JSON 或更改内容以使用允许的内容类型之一。


    仅供参考,在这种情况下,注销传入请求的重要预期方面通常会有所帮助。在这种情况下,您可以登录 content-type 并查看您得到了什么。您还可以在 Chrome 调试器的网络选项卡中查看从浏览器发送的请求。两者都可能会向您显示与内容类型相关的内容。

    【讨论】:

    • 好的,所以我选择停止使用no-cors 以及如何解决Access to fetch at *** from origin *** has been blocked by CORS policy 的问题?浏览器告诉我使用no-cors
    • 我现在允许所有的 cors documentation
    • @Himynameis - 您必须在服务器上允许 cors 请求,对于非简单请求,您可能还必须启用飞行前请求。不能从浏览器绕过 COR - 它必须在服务器上允许。
    猜你喜欢
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    相关资源
    最近更新 更多