fetch获取Json数据失败,不设置mode属性失败,设置mode为"cors","no-cors"也失败:
fetch('http://www.sojson.com/open/api/weather/json.shtml?city=%E6%88%90%E9%83%BD', {
method: 'GET',
mode: 'no-cors'
}).then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error()
}
}).then(data => {
console.log(data);
}).catch(err => {
console.error('error:'+err);
});
axios获取Json数据成功:
var axios = require('axios');
axios.get('http://www.sojson.com/open/api/weather/json.shtml?city=%E6%88%90%E9%83%BD')
.then(function (response) {
console.log(response.data);
})
.catch(function (err) {
console.log(err);
});
出现这种情况是什么原因?fetch到底该怎么调用?
你这个请求跨域了,fetch 对于跨域请求比较严格。
设置 no-cors 表示该不跨域,这时请求能成功返回,但是不能读取响应体。response.json() 会报错。
设置 cors 表示跨域,必须服务器设置 Access-Control-Allow-Origin 头,否则请求不会返回。
所以你设置 no-cors 和 cors 都不行。