Reputation: 51
I set up a REST Server and I can send http requests via Postman. That works fine. Now I am trying to send a GET request from this server to another server.
Let me show you:
const express = require('express');
const XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
const router = express.Router();
router.get('/', (req, res, next) => {
const http = new XMLHttpRequest();
const url = 'https://jsonplaceholder.typicode.com/posts';
// Postman Mock
//const url = '...';
http.open("GET", url);
http.send();
http.onreadystatechange = function() {
console.log(this.readyState, this.status);
console.log(this.statusText);
if (this.readyState == 4 && this.status == 200){
console.log("It worked!");
console.log(http.responseText);
}
}
res.status(200).json({
message: 'Handling GET requests to /product'
});
});
module.exports = router;
I send a GET request via Postman to my server and that should trigger another GET request from my server to the jsonplacholder. But I get this:
4 0
Error: connect ETIMEDOUT ... at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1128:14) { errno: 'ETIMEDOUT', code: 'ETIMEDOUT', syscall: 'connect', address: '...', port: ... }
There is no HTTP Code 0 ...
Besides I tried this:
<!DOCTYPE html>
<html>
<body>
<h2>The XMLHttpRequest Object</h2>
<script>
const Http = new XMLHttpRequest();
const url='https://jsonplaceholder.typicode.com/posts';
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
console.log("TEST");
console.log(Http.readyState, Http.status);
console.log(Http.responseText)
}
</script>
</body>
</html>
In the Browser Console you can see this:
TEST
2 200
TEST
3 200
... an the extreme long json coming from jsonplaceholder
So it worked fine here. What am I doing wrong? And is it even possible to send a request like I tried it?
Thanks for your help! :)
Marc
Upvotes: 2
Views: 13050
Reputation: 81
Your code works just fine. It seems like you have a proxy blocking the request. You can look at this thread for adding the proxy using xmlHttpRequest Use node-XMLHttpRequest through a Proxy?.
I would recommend you use a higher level http request library like superagent https://github.com/visionmedia/superagent
Upvotes: 2