0

I'm trying to send data to index.js, in localhost it's works correctly but when I deploy to my server it's not working. I see problem seems similar : here. but it's not work for me

client.js : sending data to 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...");
}

 

then in 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});
  });
});

Request Payload

{dataSubscribe: {,…}, dataNotif: {head: "@username", content: "yo"}}
dataNotif: {head: "@username", content: "yo"}
dataSubscribe: {,…}

So, it's sending data correctly, but in index.js when I use console.log(req.body) it return empty array {}.

1 Answers1

0

Using no-cors in your fetch() means that the content-type can only be one of the following: "application/x-www-form-urlencoded", "multipart/form-data", or "text/plain" (some more explanation here). So, your "application/json" is not allowed and thus the server doesn't properly read/parse the body.

Only simple headers are allowed with no-cors which you can read about here.

You will have to stop using no-cors with your fetch to use JSON or change the content to use one of the allowed content-types.


FYI, in cases like this, it's generally helpful to log out the important expected aspects of the incoming request. In this case, you could log the content-type and see what you're getting. You could also look at the request as it's being sent from the browser in the network tab of the Chrome debugger. Either would probably show you something related to the content-type.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • ok so I choose to stop using `no-cors` and how to fix `Access to fetch at *** from origin *** has been blocked by CORS policy` than? the browser tell me to use `no-cors` – Hi mynameis Sep 25 '21 at 03:52
  • I allow all cors for now [documentation](http://expressjs.com/en/resources/middleware/cors.html) – Hi mynameis Sep 25 '21 at 04:06
  • @Himynameis - You have to allow cors requests on the server and for non-simple requests, you may also have to enable pre-flight requests. CORs cannot be bypassed from the browser - it must be allowed on the server. – jfriend00 Sep 25 '21 at 04:11