Vue使用Fetch请求接口返回(Uncaught (in promise) Error: )
Uncaught (in promise) Error: SyntaxError: Unexpected end of input
at Object._callee$ (webpack-internal:///./src/config/fetch.js:89:31)
at tryCatch (webpack-internal:///./node_modules/regenerator-runtime/runtime.js:62:40)
at Generator.invoke [as _invoke] (webpack-internal:///./node_modules/regenerator-runtime/runtime.js:296:22)
at Generator.prototype.(anonymous function) [as throw] (webpack-internal:///./node_modules/regenerator-runtime/runtime.js:114:21)
at step (webpack-internal:///./node_modules/babel-runtime/helpers/asyncToGenerator.js:17:30)
at eval (webpack-internal:///./node_modules/babel-runtime/helpers/asyncToGenerator.js:30:13)
at <anonymous>
import {
baseUrl
} from './env'
export default async(type = 'POST', url = '', data = {}, method = 'fetch') => {
type = type.toUpperCase();
url = baseUrl + url;
if (type == 'GET') {
let dataStr = ''; //数据拼接字符串
Object.keys(data).forEach(key => {
dataStr += key + '=' + data[key] + '&';
})
if (dataStr !== '') {
dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
url = url + '?' + dataStr;
}
}
if (window.fetch && method == 'fetch') {
let requestConfig = {
credentials: 'include',
method: type,
headers: {
'Accept': 'application/json',
// 'Content-Type': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
mode: "no-cors",
cache: "force-cache"
}
if (type == 'POST') {
Object.defineProperty(requestConfig, 'body', {
value: JSON.stringify(data)
})
}
try {
var response = await fetch(url, requestConfig);
var responseJson = await response.json();
} catch (error) {
throw new Error(error)
}
return responseJson
} else {
let requestObj;
if (window.XMLHttpRequest) {
requestObj = new XMLHttpRequest();
} else {
requestObj = new ActiveXObject;
}
let sendData = '';
if (type == 'POST') {
sendData = JSON.stringify(data);
}
requestObj.open(type, url, true);
requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
requestObj.send(sendData);
requestObj.onreadystatechange = () => {
if (requestObj.readyState == 4) {
if (requestObj.status == 200) {
let obj = requestObj.response
if (typeof obj !== 'object') {
obj = JSON.parse(obj);
}
return obj
} else {
throw new Error(requestObj)
}
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
把export default后面的async去掉或者返回一个Promise对象
async 里面 先返回一个promise,然后 await 它。
应该是fetch请求返回的data不是json格式所以报错,如果是是用vue的话,不单要检查一下页面的接口,还要检查一下vuex里面的调的接口是否是返回一个json格式的数据
原因https://stackoverflow.com/que...
后台在写数据的时候,返回你的数据类型是String,而不是json,所以让后台改一下返回值的数据类型