How can node be returned to the browser after the result is obtained by calling the backend api, as the middle tier?

the leader requires that if you use node as the middle layer, request the backend api,node layer to use the koa2 (2.5.1) framework to provide an interface to the browser, but it is normal to return some dead data as a test when the backend development is not completed, but it will not be returned when you connect to the backend api. Browser http status code 404. Stubbornly use node as the middle layer, hope to spray lightly. The code is as follows

// node8.11.2
// routerkoa-router7.1.1
//  koa2-cors
// nodehttprequest2.87.0
router.post("/login", async (ctx, next) => {
  console.log("", ctx.request)  // 
  console.log("", ctx.request.body) // 
  console.log("", ctx.request.body.name, "", ctx.request.body.password) // 
    ctx.body = {  // login
     code: 200,
     msg: "success"
   }
/*
* request
* 
*/
   request({
    url: "http://xxx.55.41.71:9090/tokens",
    method: "POST",
    json: true,  // true
    headers: {
      "content-type": "application/json",
    },
    body: JSON.stringify({
      "userName": ctx.request.body.name,
      "password": ctx.request.body.password
    })
  }, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      console.log(body)  // body
      ctx.body = body  // 
    }
  })
})

as shown in figure

if my browser needs to call the node layer, the interface of the node layer needs to access three interfaces, namely, AMagi BMagc. Only when the three APIs of AMagi B C get the data can it be returned to the browser (assuming there is no dependency). Is there a method similar to all?

Mar.18,2021

the request has already been returned when you set the ctx.body, callback in the requrest callback.

you should use async/await, something like this:

const request = require('request-promise-native');
const Koa = require('koa');

const app = new Koa();

app.use(async ctx => {
    let res = await request("https://www.mocky.io/v2/5185415ba171ea3a00704eed")
    ctx.body = res
});

app.listen(3000);

request is packaged with promise: request-promise-native .


ctx.response.status = 200 // 
ctx.body = {
 ... 
}
Menu