简体   繁体   中英

How to show result body from node JS request to browser?

I new to nodeJS and i want to show my request result body to browser using express, but this code throw an error like this, i've try to use array.push() but not working too

ERROR

node:_http_outgoing:576
    throw new ERR_HTTP_HEADERS_SENT('set');
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:371:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
    at ServerResponse.header (C:\xampp\htdocs\#masgalih\tt\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (C:\xampp\htdocs\#masgalih\tt\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (C:\xampp\htdocs\#masgalih\tt\node_modules\express\lib\response.js:267:15)
    at ServerResponse.send (C:\xampp\htdocs\#masgalih\tt\node_modules\express\lib\response.js:158:21)
    at Request._callback (C:\xampp\htdocs\#masgalih\tt\index.js:12:24)
    at Request.self.callback (C:\xampp\htdocs\#masgalih\tt\node_modules\request\request.js:185:22)
    at Request.emit (node:events:390:28)
    at Request.<anonymous> (C:\xampp\htdocs\#masgalih\tt\node_modules\request\request.js:1154:10) {
  code: 'ERR_HTTP_HEADERS_SENT'
}

CODE

const request = require('request')
const express = require('express')
const app = express()

app.get('/getdata', (req, res) => {
    if (req.query.id !== undefined && req.query.id !== '') {
        request('http://localhost/myApi/index.php?id=' + req.query.id, (err, response, body) => {
            return res.send({
                status: 200,
                data: body
            })
        })
    }

    return res.send({
        status: 400,
        msg: 'Parameter invalid'
    })
})

app.listen(2000)

The app.get('/getdata'); has two different res.send(); 's in it. This by itself is alright, but what is happening is that when the function in app.get('/getdata');runs, it checks that if statement first. If the if is false, it skips right past and everything runs fine.

But what if the if statement is true? Well, the code inside the the statement runs and sends a request to the specified URL and waits for a response. While it's waiting though, JavaScript continues running your code because JavaScript is asynchronous .

So the second res.send() runs, but then the response to the request is received, and therefore sends a second (the first in chronological order) res.send() , which is why the error is saying you are trying to set headers (the main information in a nodejs request) after you just sent it to the client.

What the code should do is instead only run on or the other, not both. We can achieve this by putting the second res.send() in an else, which means it only runs if the if statement is false. So something like this:

const request = require('request')
const express = require('express')
const app = express()

app.get('/getdata', (req, res) => {
    if (req.query.id !== undefined && req.query.id !== '') {
        request('http://localhost/myApi/index.php?id=' + req.query.id, (err, response, body) => {
            return res.send({
                status: 200,
                data: body
            })
        })
    } else {

        return res.send({
            status: 400,
            msg: 'Parameter invalid'
        })
    }
})

app.listen(2000)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM