0

as shown in the code posted below, for the front-end part, I invoking the webservice getTIFFForSubsetAsNIRRange/ and I want to send the contents shown in body the webservice is invoked successfully but i can not get the body posted to it.

As shown below in the back-end side, I used req.data but it returns undefined

Please let me know how to have access to the contents sent to the backend

attempts to solve it

let data = req.body;
res.send('Data Received: ' + JSON.stringify(data));

but it results in an error:

UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

front-end:

drawEvt.on('drawend', e => {
    let feature = e.feature;
    let geom = feature.getGeometry();
    let wktformat = new WKT();
    let geoJSONformat = new GeoJSON();
    let wktRepresenation = wktformat.writeGeometry(geom);
    let geoJSONRepresentation = geoJSONformat.writeGeometry(geom);
    this.wktRepresenation = wktRepresenation;
    this.geoJSONRepresentation = geoJSONRepresentation;
    console.info(debugTag, 'drawEvt.on' + 'wktRepresenation:', this.wktRepresenation);
    console.info(debugTag, 'drawEvt.on' + 'geoJSONRepresentation:', this.geoJSONRepresentation);
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ wktRepresenation: this.wktRepresenation }),
,
    };
            
    fetch('http://localhost:4000/getTIFFForSubsetAsNIRRange/', requestOptions)
        .then(response => response.json())
        .then(data => (this.postId = data.id));
});

back-end

app.post('/getTIFFForSubsetAsNIRRange/', async (req, res, next) => {
    console.log(res.send(req.body))
    return 'OK'
});

app.listen(port, () => {
    console.log('listening to port', port);
});
Amrmsmb
  • 1
  • 27
  • 104
  • 226
  • Why `await res.json()`, when what you are sending isn't JSON at all? – CBroe Jul 27 '23 at 10:53
  • _body: 'Vue POST Request Example'_ - what are you really trying to send to the server? – traynor Jul 27 '23 at 11:13
  • right, that was the problem, it's not `text`, it's JSON, try: `headers: { 'Content-Type': 'application/json' },`, and remove `await` from `res.json`. Also, it's `req.body` to access posted data, not `req.data`, so it's `req.body.wktRepresenation` – traynor Jul 27 '23 at 11:18
  • ..and remove `return res.send(req.body)`, because `res.json` already sends the response and ends it, and using `res.send` afterwards throws that error – traynor Jul 27 '23 at 11:23
  • @traynor i adapted the code as you suggested but still i can not have the contents `body: JSON.stringify({ wktRepresenation: this.wktRepresenation })` posted to the back-end, i want the backend to receive `body: JSON.stringify({ wktRepresenation: this.wktRepresenation })` please – Amrmsmb Jul 27 '23 at 11:24
  • you're still sending `req.data` in `res.json`, which is undefined.. use `console.log(req.body)`, it should show JSON that you posted, if not, you need to setup JSON parser, see: [How do I consume the JSON POST data in an Express application](https://stackoverflow.com/questions/10005939/how-do-i-consume-the-json-post-data-in-an-express-application) – traynor Jul 27 '23 at 11:28
  • @traynor now the body of the webservice contains only `console.log(res.send(req.body))` and the result of req.body is a huge object represented in key-value and i can not find the data posted from the front-end which is the `wktRepresenation` – Amrmsmb Jul 27 '23 at 11:37

1 Answers1

1

Use res.json to send back JSON data:

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

    console.log('posted wktRepresenation  is:\n', req.body.wktRepresenation);

    // do something with req.body.wktRepresenation

    // send back some json
    res.json({myProperty:'myProperty value'}); // should show in  response.json()
});

To summarize, you need to:

  • post JSON request with fetch
  • setup JSON parser on the server to process posted JSON
  • use req.body to access posted data
  • use res.json to send back some JSON data
traynor
  • 5,490
  • 3
  • 13
  • 23
  • thanks, but `req.body.wktRepresntation` returns ' Cannot read property 'wktRepresenation' of undefined' despite the `wktRepresentatio` has value in the front-end – Amrmsmb Jul 27 '23 at 11:50
  • did you setup `app.use(express.json());`, also, it's not clear what `this.wktRepresenation` is, so try maybe posting some dummy data, for example: `body: JSON.stringify({wktRepresenation:'Vue POST Request Example'}),`, to make sure that part works, and then try the real data, if it doesn't work then there's some problem there.. – traynor Jul 27 '23 at 11:57
  • yes, now after i set up app.use(express.json)); it worked – Amrmsmb Jul 27 '23 at 11:59
  • should this line `res.json({myProperty:'myProperty value'});` as mentioned in your answer be posted to the front-end? ii mean, res.json will send such contents to the front-end? – Amrmsmb Jul 27 '23 at 12:01
  • 1
    yes, you can send back object with error message or success message, for example: `res.json({result:'OK'})`, or `res.json({result:'Error'})`, but you don't need to send back anything, if your goal is only to send data to the server, in that case you can simply end the response with 200: `res.sendStatus(200);`, but you should probably have some error handlers and add corresponding action on the frontend (for example, utilize fetch's `response.ok`) – traynor Jul 27 '23 at 12:10
  • just in case this question is interesting for you :https://stackoverflow.com/questions/76779731/how-to-send-data-from-backend-webservice-to-the-frontend – Amrmsmb Jul 27 '23 at 12:26