在我的项目中,我使用此经过修改的axios函数来发出API请求:
// api.js
function request (method, path, { query, params }, fields) {
query = escapeQuery(query); // make query string
return axios[method](`${API.URL}${path}?${query}`, {
...fields,
params
});
}
let methods = {};
['post', 'get', 'patch', 'delete', 'put'].forEach(method => {
methods[method] = (...args) => request(method, ...args);
});
所以在实际情况下,像这样:
import API from 'api.js';
...
getSomePages (state) {
var config = {
headers: { 'x-access-token': state.token }
};
let query = { 'page': state.selected_page };
return new Promise((resolve, reject) => {
API.get(`/myapipath`, {query}, config).then(...);
});
},
...
当我像上面那样呼叫API.get()
时,效果很好。问题是当我打电话给API.post
时。似乎无法区分正确的字段。例如,当我打电话时:
likePost (state, post_id, user_id) {
var config = {
headers: {
'x-access-token': state.token,
'Content-Type': 'application/x-www-form-urlencoded'
}
};
var data = {
post_id, user_id
};
return new Promise((resolve, reject) => {
API.post(`/myapipath`, {data}, config).then(...);
});
},
此API.post
调用一直失败,因此我查询了请求,发现它没有标题-我发送的所有字段都在请求正文中。
所以我尝试了类似的事情:
API.post(`/myapipath`, {}, config, data)...
API.post(`/myapipath`, data, config)...
API.post(`/myapipath`, {data, config})...
etc...
但是这一切都失败了。似乎所有人都无法理解哪个是标头。我该怎么解决?