express跨域设置_跨域post请求

express跨域设置_跨域post请求,第1张

express跨域设置_跨域post请求 最近在学习express,就用以前做的项目来进行express前后端分离的练手了,在做登陆注册的时候发现跨域的时候,session的值是会失效的,导致session里面的数据获取为undefined,网上找资料加上自己的不断尝试,终于找到了解决方法,简单记录一下解决方法。

1、客户端因为session原则上是需要cookie支持的,所以Ajax方法里面必须添加 xhrFields:{withCredentials:true},表示允许带Cookie的跨域Ajax请求( 特别说明,只要使用的session都得加这句) $('#login').click(function () { $.ajax({ url: 'http://localhost:3000/users/yzm',//服务端路由地址 type: 'get', xhrFields:{withCredentials:true}, dataType: 'json', success:function(data){ $('#yzm_img').html(data) }, error:function(){ alert('error'); } }); }); $('#form_login').submit(function (e) {/!*登录*!/ e.preventDefault();/!*阻止表单默认事件,页面全局刷新*!/ var data=$('#form_login').serialize();/!*将表单里的数据包装起来*!/ $.ajax({ url : 'http://localhost:3000/users/login', type : "post", data : data, xhrFields:{withCredentials:true}, dataType:'json', success:function(msg) { alert("这是返回的数据"+msg); }, error:function(err){ alert("这是失败的信息"+err); } }); });通过设置 withCredentials: true ,发送Ajax时,Request header中便会带上 Cookie 信息。

2、服务器端修改app.js文件相应的,对于客户端的参数,服务器端也需要进行设置。

对应客户端的xhrFields.withCredentials: true 参数,服务器端通过在响应 header 中设置 Access-Control-Allow-Credentials = true 来运行客户端携带证书式访问。

通过对 Credentials 参数的设置,就可以保持跨域 Ajax 时的 Cookie。

var express = require('express');var session = require('express-session');/*引入会话变量*/var app = express();app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "http://localhost:63342");//前端域名 res.header("Access-Control-Allow-Credentials",'true'); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); next();});特别注意:服务器端Access-Control-Allow-Credentials = true时,参数Access-Control-Allow-Origin 的值不能为 ‘*’ ,必须为自己客户端项目所在地址。

3、服务器中使用sessionrouter.get('/yzm', function(req, res, next) { req.session.yzm='abcd';}router.post('/login', function(req, res, next) { console.log(req.session.yzm);}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/667604.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-18
下一篇 2022-04-18

发表评论

登录后才能评论

评论列表(0条)

保存