我好几天都被困在这个axios post的请求上。我正在尝试向REST API发送一个post请求,以便它可以在后端创建一个新的数据条目。
在使用axios以及XSRF令牌和CSRF令牌发送帖子请求后,我总是得到“OPTIONS / endpointURL HTTP / 1.1”200 0“而不是实际的帖子请求:
这是我的axios post请求代码
import axios from '../helpers/axios';
axios({
method: "post",
url: "http://endpointurl",
withCredentials: true,
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': localStorage.getItem('xsrftoken'),
'csrftoken': localStorage.getItem('csrftoken')
// 'XSRF-TOKEN': localStorage.getItem('userToken')
},
data: {
name: this.state.name,
}
}).then(res => {
console.log(res);
console.log(res.data);
})
我还尝试发送错误的令牌以及帖子请求,我仍然会得到“OPTIONS ......”
../助手/ Axios公司
import axios from 'axios'
/**
* Config global for axios/django
*/
axios.defaults.xsrfHeaderName = "X-CSRFToken"
axios.defaults.xsrfCookieName = 'csrftoken'
export default axios
这就是我获得令牌的方式
// using jQuery
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
var xsrftoken = getCookie('XSRF-TOKEN');
localStorage.setItem('csrftoken', csrftoken);
localStorage.setItem('xsrftoken', xsrftoken);
谢谢!