温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

javascript怎么在跨域请求中携带cookie

发布时间:2022-03-02 12:30:57 来源:亿速云 阅读:1009 作者:小新 栏目:开发技术

这篇文章给大家分享的是有关javascript怎么在跨域请求中携带cookie的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

1. 搭建环境

1.生成工程文件

npm init

2.安装 express

npm i express --save

3.新增app1.js,开启服务器1 端口:3001

const express = require('express') const app = express() const port = 3001 // 设置`cookie` app.get("/login", (req, res) => {     res.cookie("JESSIONID", "10101001", { maxAge: 2000000, httpOnly: true });     res.json({ code: 200, message: "登录成功" });   });    // 检测浏览器是否会自动携带上`cookie` app.get("/getUser", (req, res) => { const user = req.headers.cookie.split("=")[1]; res.json({ code: 200, user }); }); // 静态资源在public目录下 app.use("/", express.static("public"));    app.listen(port, () => {   console.log(`Example app listening on port ${port}`) })

4.新增app2.js,开启服务器2 端口:3002

const express = require('express') const app = express() const port = 3002 app.get("/crossList", (req, res) => {   res.json({ code: 200, msg: "这是3002端口返回的" }); }); app.listen(port, () => {   console.log(`Example app listening on port ${port}`) })

5.新增public文件夹,新建index.html文件

<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <meta http-equiv="X-UA-Compatible" content="IE=edge">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <title>Document</title>     <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body>     <div>         <button id="button">同源请求</button>         <button id="crossButton">跨域请求</button>     </div>     <script>         const button = document.querySelector("#button");         const crossButton = document.querySelector("#crossButton");            axios.get("http://localhost:3001/login", {}).then((res) => {           console.log(res);         });         // 发送同域请求         button.onclick = function () {           axios.get("http://localhost:3001/getUser", {}).then((res) => {             console.log(res);           });         };         // 发送跨域请求         crossButton.onclick = function () {           axios({             method: "get",             url: "http://localhost:3002/crossList",           }).then((res) => {             console.log(res);           });         };       </script>    </body> </html>

6.分别启动两个服务

  • node app1.js

  • node app2.js

7.项目目录如下

javascript怎么在跨域请求中携带cookie

至此,环境搭建好了,在浏览器访问http://localhost:3001/index.html即可。

javascript怎么在跨域请求中携带cookie

我们把资源部署到了服务器1上,即端口3001。同源请求的是3001的接口,跨域请求的是3002的接口。

2. 测试同源cookie

加载index.html会自动请求login接口,获取cookie

javascript怎么在跨域请求中携带cookie

javascript怎么在跨域请求中携带cookie

点击同源请求按钮,发送同源请求,getUser接口请求会自动携带cookie

javascript怎么在跨域请求中携带cookie

3. 跨域请求携带cookie

点击跨域请求按钮

javascript怎么在跨域请求中携带cookie

解决:
1.axios请求时加上 withCredentials: true,再次点击跨域请求

crossButton.onclick = function () {   axios({      withCredentials: true, // ++      method: "get",      url: "http://localhost:3002/crossList",    }).then((res) => {      console.log(res);    });  };

javascript怎么在跨域请求中携带cookie

2. 在服务端设置Access-Control-Allow-Origin
在app2.js中加入

app.all("*", (req, res, next) => {    res.header("Access-Control-Allow-Origin", "http://localhost:3001");  // ++    next(); });

javascript怎么在跨域请求中携带cookie

3. 在服务端设置Access-Control-Allow-Credentials
在app2.js中加入

app.all("*", (req, res, next) => {    res.header("Access-Control-Allow-Origin", "http://localhost:3001");    res.header("Access-Control-Allow-Credentials", "true"); // ++     next(); });

javascript怎么在跨域请求中携带cookie

到此,我看可以看到跨域请求中加上了cookie。

4. 总结

1.前端请求时在request对象中配置"withCredentials": true;
2.跨域服务端在response的header中配置"Access-Control-Allow-Origin", “http://xxx:${port}”;
3.跨域服务端在response的header中配置"Access-Control-Allow-Credentials", “true”

5. 知识点

1.withCredentials
该XMLHttpRequest.withCredentials属性是一个布尔值,指示是否Access-Control应使用 cookie、授权标头或 TLS 客户端证书等凭据进行跨站点请求。设置withCredentials对同站点请求没有影响。
此外,此标志还用于指示何时在响应中忽略 cookie。默认值为false. XMLHttpRequest来自不同域的 cookie 不能为自己的域设置 cookie 值,除非在发出请求之前withCredentials设置为。true通过设置为 true 获得的第三方 cookiewithCredentials仍将遵循同源策略,因此请求脚本无法通过document.cookie或从响应标头访问。 &mdash;来自MDN

2.Access-Control-Allow-Origin
指定了该响应的资源是否被允许与给定的origin共享

3.Access-Control-Allow-Credentials
当请求的凭证模式 ( ) 为Access-Control-Allow-Credentials时,响应标头告诉浏览器是否将响应暴露给前端 JavaScript 代码。 Request.credentialsinclude

当请求的凭据模式 ( Request.credentials) 为 时,如果值为include,浏览器只会将响应暴露给前端 JavaScript 代码。 Access-Control-Allow-Credentialstrue

凭据是 cookie、授权标头或 TLS 客户端证书。

当用作对预检请求的响应的一部分时,这表明是否可以使用凭证发出实际请求。请注意,简单GET 的请求不会被预检。因此,如果对具有凭据的资源发出请求,并且如果此标头未与资源一起返回,则响应将被浏览器忽略并且不会返回到 Web 内容。
Access-Control-Allow-Credentials头与 XMLHttpRequest.withCredentials属性或 Fetch API 构造函数中的credentials选项一起使用。Request()对于带有凭据的 CORS 请求,为了让浏览器向前端 JavaScript 代码公开响应,服务器(使用 Access-Control-Allow-Credentials标头)和客户端(通过为 XHR、Fetch 或 Ajax 请求设置凭据模式)都必须表明它们&rsquo;正在选择包括凭据。

感谢各位的阅读!关于“javascript怎么在跨域请求中携带cookie”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI