【发布时间】:2018-11-12 04:21:43
【问题描述】:
我正在尝试使用 axios 向 ubuntu vps(a django backend) 上的端点执行发布请求。该 api 响应在成功发布请求后创建的 201。使用 Postman,我能够成功执行发布请求,但是当我使用 Axios 尝试它时,我可以看到控制台中捕获了异常(我使用了 console.log)。
这是我通过 Axios 进行的操作:
.
.
.
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = 'X-CSRFToken'
// Tried without headers as well
var headers = {'Content-Type': 'application/x-www-form-urlencoded'}
axios.post('http://127.0.0.1:8000/api/v1/subscribe/',data_str,headers)
.then(function(response) {
console.log('saved successfully');
// this.isHidden = false;
alert("Subscription succesful !!");
console.log(response)
}).catch((error) =>{
if(error.response){
console.log('1..........Response Error');
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
}
else if(error.request){
// This part gets printed in the browser console. No idea why
console.log('2..........Request Error');
console.log(error.request);
}
else{
console.log('3..........Other error');
console.log('Error', error.message);
}
console.log(error.config);
} );
var headers = {'Content-Type': 'application/x-www-form-urlencoded'}
axios.post('http://127.0.0.1:8000/api/v1/subscribe/',data_str,headers)
.then(function(response) {
console.log('saved successfully');
// this.isHidden = false;
alert("Subscription succesful !!");
console.log(response)
}).catch((error) =>{
if(error.response){
console.log('1..........Response Error');
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
}
else if(error.request){
console.log('2..........Request Error');
console.log(error.request);
}
else{
console.log('3..........Other error');
console.log('Error', error.message);
}
console.log(error.config);
} );
**我的 django rest api 中很少有 CORS 配置:
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_METHODS = ['DELETE','GET','OPTIONS','PATCH','POST','PUT',]
CORS_ALLOW_HEADERS = ['*']
这是控制台This is the console log in browser中的错误图片
如果有人提供帮助,我将不胜感激。
提前致谢!
【问题讨论】:
-
服务器是否被请求命中?
-
你能否检查一下如果你在 chrome 上尝试这个会发生什么,它可能会在 OPTIONS 请求中失败,这会有所帮助
-
没有。发布请求甚至没有到达服务器
-
@supra28 这是 Chrome 日志的截图:我不知道 chrome 中的 OPTIONS 在哪里
标签: javascript django vue.js postman axios