我在我的项目中使用 VueSession。我创建了一个登录组件,并将数据传递到后端(Django,返回 JWT token )。这是我的问题。我的登录工作正常,它返回 JWT,但是当我想从其他端点获取数据时,我收到错误 401 ( Authentication credentials were not provided
)。当我在终端中使用curl 时,一切正常。
curl -X POST -d "username=test&password=test" http://localhost:8000/api/token/auth/
它返回 token
curl -H "Authorization: JWT <my_token>" http://localhost:8000/protected-url/
它从网站返回数据
这是我在 Vue 项目中设置的内容。
Login.vue
<script>
import Vue from 'vue'
export default {
name: 'Login',
data () {
return {
username: '',
password: ''
}
},
methods: {
login: function (username, password) {
let user_obj = {
"username": username,
"password": password
}
this.$http.post('http://192.168.1.151:8000/api/token/auth', user_obj)
.then((response) => {
console.log(response.data)
this.$session.start()
this.$session.set('jwt', response.data.token)
Vue.http.headers.common['Authorization'] = 'JWT' + response.data.token
// this.$router.push('/')
})
.catch((error_data) => {
console.log(error_data)
})
}
}
}
</script>
HereIWantUserGETRequest.vue
<script>
export default {
data() {
return {
msg: "Welcome",
my_list: []
}
},
beforeCreate() {
// IF SESSION DOESN'T EXIST
if (!this.$session.exists()) {
this.$router.push('/account/login')
}
},
mounted() {
this.getData()
},
methods: {
getData: function() {
this.$http.get('http://192.168.1.151:8000/api/user/data')
.then((response) => {
console.log(response.data)
this.my_list = response.data
})
.catch((error_data) => {
console.log(error_data)
})
}
}
}
</script>
当然,我在 main.js 中设置了 VueSession 和 VueResource
import VueSession from 'vue-session'
import VueResource from 'vue-resource'
Vue.use(VueResource)
Vue.use(VueSession)
最佳答案
编辑
Vue.http.headers.common['Authorization'] = 'JWT' + response.data.token
与
Vue.http.headers.common['Authorization'] = 'JWT ' + response.data.token
希望对你有帮助
关于javascript - 授权 header 不适用于 http GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50132989/