简体   繁体   English

为什么 fetch 总是在这里返回 undefined?

[英]Why is fetch always returning undefined here?

I am working on a Unit Conversion API, and I am having a lot of issues with fetch().我正在处理单位转换 API,并且我在 fetch() 方面遇到了很多问题。 My backend API is working, for example, when I call curl "http://localhost:8000/unitconv/convert?to=lb&from=kg&value=10" I get the correct response: {"units": "lb", "value": 22.04623} .我的后端 API 正在工作,例如,当我调用curl "http://localhost:8000/unitconv/convert?to=lb&from=kg&value=10"我得到正确的响应: {"units": "lb", "value": 22.04623} Yet when I do the exact same thing with fetch(), this is what I get:然而,当我用 fetch() 做同样的事情时,我得到的是: 截屏 I have tried both localhost and 127.0.0.1 and I still cannot get past this "undefined".我已经尝试了 localhost 和 127.0.0.1 ,但我仍然无法通过这个“未定义”。 What's wrong here?这里有什么问题?

You are using a curly bracket in the first then without a return so nothing is going to the second then.您在第一个中使用了一个大括号,然后没有返回,所以第二个没有任何内容。 It should be它应该是

.then((response) => {return response.json()}).then(() => ...

You can simply omit the curly brackets like this:您可以像这样简单地省略大括号:

fetch(url).then(response => response.json()).then(() =>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM