The problem of jumping error report after fetch in node.js

after receiving the access request, my task is to first use fetch to obtain data, and then use response.setHeader ("Location"," http://www.b.com")) to jump, but the jump is not successful and an error is reported on the node server. The
code is as follows:

import fetch from "node-fetch";

let ret = await fetch("http://www.a.com");
let data = await ret.json();
//response
response.setHeader("Location","http://www.b.com");
response.statusCode = 302;
response.end();

the error prompt is as follows:

Error: Can"t set headers after they are sent.

but if you put fetch behind, you can jump successfully without reporting an error. The code is as follows:

import fetch from "node-fetch";

//response
response.setHeader("Location","http://www.b.com");
response.statusCode = 302;
response.end();

let ret = await fetch("http://www.a.com");
let data = await ret.json();

but my goal of getting the data first and then jumping is not achieved.
so how to solve this problem?

Mar.23,2021

if you are using Express, try the redirect method
there is a similar problem for reference: https://stackoverflow.com/que.


when you response, you must wait for the request to come back before setting

.
Menu