分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

前后端分离 ajax 跨域 session 传值 (后端使用 node)

发布时间:2023-09-06 02:20责任编辑:傅花花关键词:后端跨域

前端:ajax访问时要加上“xhrFields: {withCredentials: true}” ,实现session可以传递

后端:Access-Control-Allow-Credentials 设置为 true;同时 Access-Control-Allow-Origin 必须指定 url
 

npm 安装 express、body-parser、express-session、svg-captcha

后台代码:

 1 var express = require(‘express‘); 2 var app = express(); 3 var svgCaptcha = require(‘svg-captcha‘); // 动态验证码 4 var session = require(‘express-session‘); 5 var bodyParser = require(‘body-parser‘); // Express框架请求体解析的中间件 6 ?7 var urlencodedParser = bodyParser.urlencoded({ extended: false }); 8 ?9 app.use(session({10 ??resave: true, // don‘t save session if unmodified11 ??saveUninitialized: false, // don‘t create session until something stored12 ??secret: ‘node‘13 }));14 app.use(function (req, res, next) {15 ??// Website you wish to allow to connect16 ??res.setHeader(‘Access-Control-Allow-Origin‘, req.headers.origin);17 ??// res.setHeader(‘Access-Control-Allow-Origin‘, "*");18 19 ??// Request methods you wish to allow20 ??res.setHeader(‘Access-Control-Allow-Methods‘, ‘GET, POST, OPTIONS, PUT, PATCH, DELETE‘);21 22 ??// Request headers you wish to allow23 ??res.setHeader(‘Access-Control-Allow-Headers‘, ‘X-Requested-With,content-type‘);24 25 ??// Set to true if you need the website to include cookies in the requests sent26 ??// to the API (e.g. in case you use sessions)27 ??res.setHeader(‘Access-Control-Allow-Credentials‘, true);28 29 ??// Pass to next layer of middleware30 ??next();31 });32 33 34 app.get(‘/‘, function (req, res) {35 ??res.send(‘Hello World‘);36 });37 app.post(‘/trendsCode‘, urlencodedParser, function (req, res) { 38 ??var code = req.body.code;39 ??if (code) {40 ????var response = {41 ??????msg: ‘success‘,42 ??????trendsCode: req.session.trendsCode43 ????};44 ????res.send(JSON.stringify(response));45 ??} else {46 ????var codeConfig = {47 ??????size: 5, // 验证码长度48 ??????noise: 2, // 干扰线条的数量49 ??????height: 4450 ????}51 ????var captcha = svgCaptcha.create(codeConfig);52 ????req.session.trendsCode = captcha.text;53 ????res.send(captcha.data);54 ??}55 });56 57 var server = app.listen(8080, function () {58 ??var host = server.address().address59 ??var port = server.address().port60 61 ??console.log("应用实例,访问地址为 http://%s:%s", host, port);62 });

前端代码:

 1 <!DOCTYPE html> 2 <html lang="en"> 3 ?4 <head> 5 ??<meta charset="UTF-8"> 6 ??<meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 ??<meta http-equiv="X-UA-Compatible" content="ie=edge"> 8 ??<title>ajax 跨域 session 传值</title> 9 </head>10 11 <body>12 ??<h1>trends code</h1>13 ??<div id="code"></div>14 ??<input type="text" id="input">15 ??<input type="button" value="提交" onclick="submit()">16 17 ??<script src="./jquery-3.3.1.min.js"></script>18 ??<script>19 ????window.onload = function () {20 ??????$.ajax({21 ????????url: "http://127.0.0.1:8080/trendsCode",22 ????????type: ‘POST‘,23 ????????xhrFields: {24 ??????????withCredentials: true25 ????????},26 ????????success: function (response) {27 ??????????// console.log(‘response--‘,response);28 ??????????$(‘#code‘).html(response);29 ????????},30 ????????error: function (error) {31 ??????????console.log(‘error--‘, error)32 ????????}33 ??????});34 ????};35 ????var submit = function () {36 ??????// console.log(‘submit‘);37 ??????var inputCode = $(‘#input‘).val();38 ??????$.ajax({39 ????????url: "http://127.0.0.1:8080/trendsCode",40 ????????data: {41 ??????????code: inputCode42 ????????},43 ????????type: ‘POST‘,44 ????????xhrFields: {45 ??????????withCredentials: true46 ????????},47 ????????success: function (response) {48 ??????????console.log(‘response--‘, response);49 ??????????// document.write(response);50 ????????},51 ????????error: function (error) {52 ??????????console.log(‘error--‘, error)53 ????????}54 ??????});55 ????};56 ??</script>57 </body>58 59 </html>

前端 xhrFields 的设置(XMLHttpRequest 和 jquery)

 1 // XMLHttpRequest 2 var xhr = new XMLHttpRequest(); 3 xhr.open(‘GET‘, ‘http://127.0.0.1:8080/trendsCode‘); 4 xhr.withCredentials = true; 5 xhr.onload = onLoadHandler; 6 xhr.send(); 7 ?8 // jquery 9 $.ajax({10 ????url: "http://127.0.0.1:8080/trendsCode",11 ????type: "GET",12 ????xhrFields: {13 ????????withCredentials: true14 ????},15 ????success: function (data) {16 ????????// do something17 ????}18 });

参考文章: https://blog.csdn.net/jiahao791869610/article/details/79175268

前后端分离 ajax 跨域 session 传值 (后端使用 node)

原文地址:https://www.cnblogs.com/landmass/p/9876842.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved