【发布时间】:2019-11-06 17:09:40
【问题描述】:
我正在使用 NuxtJS 的 $axios 模块,我正在与一个后端 API 进行交互,该 API 设置了一个身份验证 cookie,以便在登录后进行进一步的身份验证请求。我已经查看了 withCredentials: true,但它仍然不能正常合作。
我需要设置特定的标头值还是我的 axios 配置有问题?
我只想保留并使用从成功登录时收到的这个 cookie,并在下一个请求中使用它来发出经过身份验证的请求。
// nuxt.config.js
axios : {
...
credentials: true,
withCredentials : true,
requestInterceptor: (config, {store}) => {
config.headers.common['Content-Type'] = 'application/json';
config.headers.common['API-Key'] = 'my_api_key';
return config
},
...
},
这是我提出 axios 请求的地方
async asyncData({ $axios}) {
try {
// this response sends back an authentication cookie
const login_response = await $axios.$post("my_login_route",{
password : this.password,
username : this.email,
});
if(login_response.success){
// how i send my cookie to this route to prove im authenticated?
const authenticated = await $axios.$get("my_url");
console.log(authenticated); // always false; doesn't send cookie recieved in login $post request
}else{
console.log("Invalid username or password");
}
} catch(error) {
console.log(error);
}
}
我制作了一个测试页面,发出一个简单的请求来检查用户是否已通过身份验证。 事实证明,nuxt.config.js 中的 axios 设置并未在此处应用。
我需要 axios 配置不仅适用于基本 URL,还适用于我的 API 路由。这是我按下测试按钮时激活的测试方法:
check_auth : async function(){
try {
const response = await this.$axios.$get("https://<my_url>/Utility/IsAuthenticated/");
console.log("IS AUTH:");
console.log(response.isAuthenticated);
}catch(error){
console.log("something went wrong.");
}
},
用于 AXIOS 请求的 HTTP 请求标头
如您所见,我在 axios 配置中没有指定 cookie 或 API-Key 标头。
Host: <my_url>
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:67.0) Gecko/20100101 Firefox/67.0
Accept: application/json, text/plain
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: http://localhost:1337/send/account
Origin: http://localhost:1337
DNT: 1
Connection: keep-alive
我需要在我的 axios nuxt.config.js 部分更改什么以允许 axios 配置应用于我的 api 路由?我需要使用proxy:{} 部分吗?
请帮忙!!
【问题讨论】:
-
那么 auth 令牌在 cookie 标头中作为 Cookie 返回?
-
是的,成功登录的响应有一个设置的 cookie 标头。这一切都适用于邮递员
-
可以添加更多信息吗?登录网址是什么?你能显示返回的cookie吗?您是否在配置级别设置了 baseurl?
标签: javascript http module axios nuxt.js