【问题标题】:Express api fetch request returns undefined [duplicate]Express api fetch请求返回未定义的[重复]
【发布时间】:2019-10-13 10:57:59
【问题描述】:

编辑:我在这里不问任何关于 cors 的问题

所以我花了好几个小时试图弄清楚发生了什么事,好吧......我正在失去它......

所以我有一个简单的应用程序,它的服务器部分是用 nodejs 制作的,前端是 react 的,它们在不同的端口上运行,所以我使用了 cors 模块。

无论如何 所以这是我使用 express 的 nodejs api

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.get('/', (req, res) => {
  res.send({data:"Hello"});
});
app.listen(port, () => console.log(`Listening on port ${port}`));

然后从响应下面的获取请求

    fetch("http://www.localhost:5000/",{
        method: 'GET',
        mode: "no-cors",
        cache: "no-cache", 
        credentials: "same-origin", 
        headers: {"Content-Type": "application/json"}
      })
    .then(res=>{
        console.log("res1",res)
        res.text();
    })
    .then(res=>{
        console.log("res2",res)
    })
    .catch(res=>{
        console.log("Exception : ",res);
    })

问题是无论我尝试什么,这个 req 都会返回 undefined。 在 res 1 中,响应是一个对象(在这种情况下是不透明的)

响应 {type: "opaque", url: "", redirected: false, status: 0, ok: 错误,……}

而且 res2 是未定义的。

我错过了什么?

【问题讨论】:

  • 您需要为每个then 调用返回一个值,以便将其传递下去。
  • 如果您不是在询问 CORS,为什么要这样标记您的问题?仅使用您所问的关于的内容进行标记,而不是您的问题包含

标签: node.js reactjs express fetch-api


【解决方案1】:
fetch("http://www.localhost:5000/",{
        method: 'GET',
        mode: "no-cors",
        cache: "no-cache", 
        credentials: "same-origin", 
        headers: {"Content-Type": "application/json"}
      })
    .then(res=>{
        console.log("res1",res)
        return res.text();
    })
    .then(res=>{
        console.log("res2",res)

    })
    .catch(res=>{
        console.log("Exception : ",res);
    })

【讨论】:

  • 谢谢你..我累了..也许很愚蠢......我的问题很愚蠢......道歉
  • 一切都好。这里没有任何问题是愚蠢的。乐意效劳。请务必将答案标记为已接受,以便其他人从中受益。
猜你喜欢
  • 2017-10-07
  • 2021-01-05
  • 1970-01-01
  • 2018-08-09
  • 2021-01-28
  • 2012-12-04
  • 2017-06-26
  • 1970-01-01
  • 2017-11-12
相关资源
最近更新 更多