-6

I have a really basic express service on Google Cloud Run, which is built and deployed to a container. It has access set to allow unauthenticated.

I am using fetch with React on the front end to send data to the server and receive the response.

On the server, I can't seem to get the data from the body of my request? Whatever settings I use for headers etc I can't get any data out of it.

I'm using fetch clientside to send the POST request:

const sendData = async() => {        
        const response = await fetch('https://my-service.run.app', {
            method: 'POST',
            mode: 'no-cors',
            body: { mydata: "some data"},
            json: true
          });
          return response;
    }

On the server, my service is super simple. All I want at the moment is to send json from the client to the cloud run server, log it, then send the same data back to the client as the response. However, the console log always gives me an empty object.

const express    = require('express');
const app        = express();
const bodyParser = require('body-parser');
const {Storage}   = require('@google-cloud/storage');
const cors = require('cors');

const corsOptions = {
    origin: true,
    mode: 'no-cors',
    optionsSuccessStatus: 200
};

const port = process.env.PORT || 8080;

app.use(bodyParser.json());

app.listen(port, () => {

  console.log('Listening on port', port);

});


app.post('/', async (req, res) => {

    try {

        const corsMiddleware = cors(corsOptions);

        return corsMiddleware(req, res, () => {
            const servicedata = req.body;
            console.log("MY DATA", servicedata )
            res.send(srcontext);
        });

    }

    catch (ex) {
        console.log(`Error: ${ex}`);
    }

})
Davtho1983
  • 3,827
  • 8
  • 54
  • 105

1 Answers1

5

The problem is your first code. In the documentation of node-fetch it is mentioned that when making JSON POST you should add the header headers: { 'Content-Type': 'application/json' } which is not present in your code.

Then, your code should be something like this

const sendData = async() => {        
        const response = await fetch('https://my-service.run.app', {
            method: 'POST',
            mode: 'no-cors',
            body: JSON.stringify({ "mydata": "some data"}),
            headers: { 'Content-Type': 'application/json' }
            json: true
          });
          return response;
 }

The option json:true is only for parsing the response as json, but not the request.

EDIT

As @sebastian-simon suggested: ({ mydata: "some data" }) and ({ "mydata": "some data" }) are equivalent expressions and result in equivalent objects. If mydata is a string or symbol variable, then ({ [mydata]: "some data" }) would need to be used.

Puteri
  • 3,348
  • 4
  • 12
  • 27