表达 CORS 响应

Express CORS response

我正在使用 express return 通过请求调用检索的 api 响应。

router.post('/', function(req, res){

   var options = {
      ...
   }

   rp(options)
        .then(function (parsedBody) {
            console.log(parsedBody); 
            res.json(parsedBody)
        })

控制台日志显示预期的有效载荷,当我使用 Postman 时我也看到预期的有效载荷。

当我的客户端应用程序收到响应时:

Response {type: "cors", url: "http://localhost:3001/api/", redirected: false, status: 200, ok: true, …}

我试过添加 CORS 中间件:

app.use(function(request, response, next) {
    response.header("Access-Control-Allow-Origin", "*");
    response.header("Access-Control-Allow-Headers", 
                    "Origin, X-Rquested-With, Content-Type, Accept");
    next();
});

我的客户端是一个使用 fetch 的非常简单的 React 应用程序:

fetch('http://localhost:3001/api/', {
    method: 'POST',
    dataType: 'JSON',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: data,
}).then((response) => {
      console.log(response);
   }).catch((response) => {
          console.log('Error');
   });

我的 React 应用程序是 localhost:3000 和 express api localhost:3001,预期的有效负载是一个非常简单的对象...

{
    athlete: {
        firstname: "Matt"
        ...
    }
}

我怎样才能将 api 请求响应转发给客户端获取成功方法?

问题与 CORS 无关,react 应用程序中的响应需要解析为 json:

.then((response) => {
    console.log(response.json());
})