gpt4 book ai didi

javascript - NuxtJS $axios 使用请求发送 Cookie

转载 作者:可可西里 更新时间:2023-11-01 16:22:38 26 4
gpt4 key购买 nike

我正在使用 NuxtJS 的 $axios 模块,我正在与后端 API 进行交互,该 API 设置为登录后进一步经过身份验证的请求的身份验证 cookie。我查看了 withCredentials: true,但它仍然不能正常合作。

我是否需要设置特定的 header 值或我的 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 请求 header 就在上面如您所见,我在 axios 配置中没有指定任何 cookie 或 API-Key header 。

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:{} 部分吗?

请帮忙!!

最佳答案

所以问题毕竟不是 axios。

我正在连接的 API 不允许外部源使用它的 cookie,一些跨源的东西。问题是 axios 在我尝试使用 fetch() 之前没有给出任何关于跨源问题的警告,这是我在控制台中看到关于服务器不允许跨源 cookie 的警告之类的,然后开始做研究。

相关:

How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

https://github.com/axios/axios/issues/853

感谢到目前为止评论中的帮助,但从外观上看,axios 库几乎没有解决这个问题,因为它是一种广泛的内置浏览器安全性。

如果有人对在浏览器客户端端有其他建议或答案,请与我们分享。

关于javascript - NuxtJS $axios 使用请求发送 Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56744269/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com