我在使用vue-resource和axios的Vue.js 2中的Authorization标头有问题(两者都是同一个问题)。 Vue在向后端发送请求时不添加标头。以下是我的代码和示例请求。服务器正在WSGIServer及其Django上运行(还不是nginx)。
请求发送时:
Access-Control-Request-Headers:“authorization,xxxxx”
代替:
授权:“JWT”
后端工作正常 - 我使用CURL检查请求和响应。
Accounts.vue:
<script>
import Account from './Account.vue';
import axios from 'axios';
export default {
data() {
return {
accounts: []
}
},
created: function () {
this.getAccounts();
},
methods: {
getAccounts() {
const token = localStorage.getItem('token');
axios.defaults.baseURL = 'http://localhost:8000';
axios.defaults.headers.common['Authorization'] = 'JWT <my_token>';
axios.get('/api/accounts/')
.then(
response => {
this.accounts = response.data;
}
)
.catch(
error => console.log(error)
);
},
}
}
</script>
常规
Request URL:http://localhost:8000/api/accounts/
Request Method:OPTIONS
Status Code:401 Unauthorized
Remote Address:localhost:8000
Referrer Policy:no-referrer-when-downgrade
响应标题
Allow:GET, POST, HEAD, OPTIONS
Content-Length:58
Content-Type:application/json
Date:Wed, 21 Jun 2017 06:59:34 GMT
Server:WSGIServer/0.2 CPython/3.5.2
Vary:Accept, Cookie
WWW-Authenticate:JWT realm="api"
X-Frame-Options:SAMEORIGIN
请求标题
Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4
Access-Control-Request-Headers:authorization,xxxxxx
Access-Control-Request-Method:GET
Connection:keep-alive
Host:localhost:8000
Origin:http://localhost:8080
Referer:http://localhost:8080/accounts
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/58.0.3029.110 Chrome/58.0.3029.110 Safari/537.36