javascript FETCH API 返回 [object Object]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30075178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
FETCH API returning [object Object]
提问by Cody Raspien
I am using FETCH API to get a value stored in a json file. That value has to go into a variable.
我正在使用 FETCH API 来获取存储在 json 文件中的值。该值必须进入一个变量。
The problem is - the variable ends up holding [object Object] as value.
问题是 - 变量最终将 [object Object] 保存为值。
var title = fetch('URL/out.json', {mode: 'cors'});
In the htaccess of the server hosting the json file, there is the line
在托管 json 文件的服务器的 htaccess 中,有一行
Header set Access-Control-Allow-Origin "*"
The json is as follows
json如下
{
lollol
}
I think the json might be the culprit.
我认为 json 可能是罪魁祸首。
I cannot find the reason for [object Object] to be the variable value.
我找不到 [object Object] 成为变量值的原因。
Can I use Fetch to get a hosted text file? I tried - couldn't get it work. - just thinking of an alternative.
我可以使用 Fetch 来获取托管文本文件吗?我试过 - 无法让它工作。- 只是想一个替代方案。
采纳答案by Justinas
回答by iJade
you need to stringify the object to convert it into JSON string.
您需要对对象进行字符串化以将其转换为 JSON 字符串。
try JSON.stringify(theObject)
尝试 JSON.stringify(theObject)
回答by whiskey 4
fetch API is very promise-oriented fetch returns a promise with a response object as a param you then need to call a method on the response to give you another promise with the result
fetch API 是非常面向承诺的 fetch 返回一个带有响应对象作为参数的承诺,然后你需要在响应上调用一个方法来为你提供另一个带有结果的承诺
heres an example i did. On the first .then() i called .json on the response so can i get my results on the next .then()
这是我做的一个例子。在第一个 .then() 我在响应中调用了 .json 所以我可以在下一个 .then() 上得到我的结果
export function newVideoAsync(videoData, url) {
return (dispatch) => {
return fetch(url, {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(videoData)
})
.then(response => response.json())
.then(jsonData => {
dispatch(videoSuccess(jsonData))
console.log(jsonData);
// find video id to redirect to that video
// client side redirect to '/video/:id'
browserHistory.push('/')
})
.catch(err => dispatch(videoError(err.message)));
};
};
回答by Admir Huric
For anyone still experiencing this issue while following correct fetch
syntax, please try to do these next steps (before pulling your hair out :)):
对于在遵循正确fetch
语法时仍然遇到此问题的任何人,请尝试执行以下后续步骤(在拔出头发之前 :)):
- clean cache from your project
- remove and reinstall external libs/modules
- restart your project
- 从您的项目中清除缓存
- 删除并重新安装外部库/模块
- 重启你的项目
回答by Cody Raspien
var myRequest = new Request('URL');
var title;
fetch(myRequest).then(function(text) {
return response.text().then(function(text) {
title= text;
alert (title);
});
});
This works.
这有效。