简体   繁体   中英

Not getting a response object from my third party API call express routes node.js

I am struggling with an API-call, since my response object is always undefined. Every console.log(res) returns undefined. This wouldn't be a problem, but I need to call res.json() to send to front-end. Unfortunately, I can't call send() on an undefined object. Here is my API call, I added some comments to explain.

  router.route("/run").post((req: any, res: any) => {
  data.source_code = req.body.code;
  axios({
    url: "http://35.205.20.238/submissions",
    method: "POST",
    data: data,
  })
    .then(async (req: any, res: any) => {
      //first call generates a token
      await new Promise((resolve) => setTimeout(resolve, 1000)); // 3 sec
      //after waiting, use the token to get the res.data.stdout which is 
      //what I want to send to frontend using res.send()
      axios
        .get("http://35.205.20.238/submissions/" + req.data.token)
        .then((req: any, res: any) => {
          console.log(req);
          if (!req) {
            console.log("no output");
          }
          finalOutput = req.data.stdout;
          console.log(req.data.stdout);
        });
    })
    .catch((err: Error) => console.log(err));
});

How can I solve this? Is it possible to send data to front-end with an undefined response-object? Or have I messed up the promise-chaining?

Maybe this API is for front-end only.

(please ignore the type-definitions on req and res for now)

My problem was that Heroku wasn't recognising my envoirement variables. It just showed up on Chrome as a CORS-error, but it was actually Heroku all along. Lesson learnt.

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