async submitForm(formName) {
this.$refs[formName].validate(async valid => {
if (valid) {
const res = await login({
username: this.loginForm.username,
password: hexMD5(this.loginForm.password)
});
console.log(res);
});
}
import {
baseUrl
} from './env'
export default async (url = '', data = {}, type = 'GET', 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'
},
mode: "cors",
cache: "force-cache"
}
if (type == 'POST') {
Object.defineProperty(requestConfig, 'body', {
value: JSON.stringify(data)
})
}
try {
const response = await fetch(url, requestConfig);
const responseJson = await response.json();
return responseJson
} catch (error) {
throw new Error(error)
}
} else {
return new Promise((resolve, reject) => {
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);
}
resolve(obj)
} else {
reject(requestObj)
}
}
}
})
}
}
现在fetch是后台接收不到的格式
request payload
{"username":"circle","password":"9b6ddeba5b33e577c07c35d8505c6072"}:
这是ajax POST这是后台能接收图中的格式
form data
username: circle
password: 9b6ddeba5b33e577c07c35d8505c6072
从network
看你前端本来就没问题,而问题就变成后端接收不到参数,那么后端可以处理什么content-type
呢?(这是接口定义的问题,人家定义不接受form data
你发过去有啥用)一开始以为你是发送请求的截图,原来是后台给的成功实例。。
当然有问题,
application/x-www-form-urlencoded
发送数据的格式是a=b&c=d
,而你发的是json
字符串,你可以用qs
模块转一下。然后以后有关
Network
的问题,有什么不成功请截个图发出来才能看到你到底发送了什么。