简体   繁体   中英

How do I call external web services from my NODEJS GAE APP

I am new to NODE JS + GAE so pls forgive newbie question.

I want my app to serve up a REST call that will consolidate the results of calls to other externally hosted API's (third parties - none GAE)

I have this javascript working from my PC but when I deploy to GAE i get "502 Bad Gateway" error (in my browser). I can't find anything in the GAE logs to help explain this error. Note my REST call is working (ie GAE is receiving the call) but is failing to make the outbound call to external web site.

Note here is sample NODE JS code that is failing (i am calling "/test"):

const express = require('express');

var http = require('http');

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;     

const app = express();   

// [START hello_world] 


app.get('/test', (req, res) => {

const Http = new XMLHttpRequest();

const url='https://www.google.com';

Http.open("GET", url);

Http.send();

Http.onreadystatechange=(e)=>{

console.log(Http.responseText)

}});



// [END hello_world]



if (module === require.main) {

  // [START server]

  // Start the server

  const server = app.listen(process.env.PORT || 8080, () => {

    const port = server.address().port;

    console.log(`App listening on port ${port}`);

  });

  // [END server]

}



module.exports = app;

It takes a while to run from my browser (ie a minute) then I get the "502 Bad Gateway" error. I this a cross site issue, ie, is GAE stopping web services calls being made from NODE JS apps to other sites?

The issue is that your request is timing out, because you are not sending any response indicating that the request is done.

To solve this, you will need to return an response on your /test handler, for example, you can add this:

res.status(200).send("ok").end();

Which returns a 200 OK response to the request, indicating that it has been correctly processed.

This change, in your /test handler, should probably be added this way:

app.get('/test', (req, res) => {
        const Http = new XMLHttpRequest();
        const url='https://www.google.com';
        Http.open("GET", url);
        Http.send();
        Http.onreadystatechange=(e)=>{
                console.log(Http.responseText)
                // Return response to '/test' handler request 
                res.status(200).send("ok").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.

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