Zac*_*Zac 8 javascript module http axios nuxt.js
我正在使用 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
},
...
},
Run Code Online (Sandbox Code Playgroud)
这是我提出 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);
}
}
Run Code Online (Sandbox Code Playgroud)
我制作了一个测试页面,通过一个简单的请求来检查用户是否通过身份验证。事实证明,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.");
}
},
Run Code Online (Sandbox Code Playgroud)
AXIOS 请求的 HTTP 请求头就在上面
如您所见,API-Key我在 axios 配置中没有指定cookie 或头。
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
Run Code Online (Sandbox Code Playgroud)
我需要在 axiosnuxt.config.js部分更改什么才能允许 axios 配置应用于我的 api 路由?我需要使用该proxy:{}部分吗?
请帮忙!!
所以问题毕竟不是axios 。
我连接的 API 不允许外部源使用它的 cookie,这是一些跨源的东西。问题是 axios 没有给出任何关于跨源问题的警告fetch(),直到我尝试使用 ,这是我在控制台中看到关于服务器不允许跨源 cookie 或其他内容的警告,并开始进行研究。
有关的:
如何在node.js上的express.js框架中启用跨域资源共享(CORS)
https://github.com/axios/axios/issues/853
感谢到目前为止评论中的帮助,但从表面上看, axios 库对此没有任何接近的修复,因为它是一个广泛的内置浏览器安全问题。
如果有人对使其在浏览器的客户端上工作有其他建议或答案,请与我们所有人分享。
| 归档时间: |
|
| 查看次数: |
5689 次 |
| 最近记录: |