【问题标题】:Post request via Axios fails while it succeeds from POSTMAN . How?通过 Axios 的发布请求失败,而从 POSTMAN 成功。如何?
【发布时间】: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


【解决方案1】:

感谢您的意见。 我解决了这个问题。执行 POST 请求的 URL 是 http://localhost:8000/api/v1/subscribe,在替换为 http://my website.com/api/v1/subscribe 后成功。

我正在使用实际 URL 执行:

http://my website.com/api/v1/subscribe 在 Postman 中,这就是它成功的原因。在 vue 中,我使用的是不断给出错误的本地主机。 ☺️

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-25
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多