So I am trying to send a request from express node.js to another URI :
router.get('/', function (req, res, next) {
http.get(URI, function(response) {
console.log("Got response: " + response.statusCode);
res.send(response);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
});
This sends back an error message as follows :
GET http://localhost:3000/login (anonymous function) @
loginButton.js:48getSync @ loginButton.js:34(anonymous function) @
loginButton.js:22
loginButton.js:25 DOMException: Failed to execute 'send' on
'XMLHttpRequest': Failed to load 'http://localhost:3000/login'.
at Error (native)
at http://localhost:3000/javascripts/index/loginButton.js:48:13
at getSync
(http://localhost:3000/javascripts/index/loginButton.js:34:12)
at HTMLButtonElement.<anonymous>
(http://localhost:3000/javascripts/index/loginButton.js:22:13)
I've tried to update it to the suggestion from : how to send Post request from node.js to another server ( java)? but the same error message is thrown. Does anyone know what could be wrong here?
With http.get
, the response
is a stream. As such, you either need to build up the entire body of the object (concatenate chunks from the stream) or you need to use a method that streams.
In express, res.send
will send the data and close the connection. It assumes you have sent the entire payload.
Instead of using .send
, use .write
which sends the incoming chunks right back out.
The adjusted code would look something like this:
router.get('/', function (req, res, next) {
http.get(URI, function(response) {
res.write(response);
}).on('end', function() {
res.end();
});
});
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.