1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Node.js使用CORS解决跨域问题

Node.js使用CORS解决跨域问题

时间:2022-04-04 07:29:31

相关推荐

Node.js使用CORS解决跨域问题

跨域的定义和同源策略

跨域前,我们先了解什么叫同源策略(有时简称为SOP)是 Web 应用安全模型中的一个重要概念。根据该策略,网络浏览器允许包含在第一个网页中的脚本访问第二个网页中的数据,但前提是两个网页具有相同的来源。源定义为URI 方案、主机名和端口号的组合。此策略可防止一个页面上的恶意脚本通过该页面的文档对象模型获得对另一个网页上敏感数据的访问权。而只要违反了同源策略的行为就是跨域。

如以下图片所示,展示了,不同的url请求在同源策略下的结果

CORS解决跨域的策略

CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。

CROS配置特点

CORS响应头设置跨域参数

Access-Control-Allow-origin 设置支持哪些域名下的请求 设置任何网站 Access-Control-Allow-Headers 设置最多九个请求头

//设置请求头,设置编码

res.setHeader(‘Content-Type’,‘text/html;charset=utf-8’)Access-Control-Allow-Methods 设置客户端允许的请求,CORS仅支持get,post,head请求,如果需要其他的请求可以添加HTTP请求CORS预检请求

跨域的需要的其他条件

1.发送请求前,必须先进行一次option请求

2.除了CROS默认支持的三种请求之外的请求

3.请求头包含自定义头部字段

4.向服务器发送application/json格式数据

CORS使用

引入依赖

npm install cors@2.8.5

主启动文件

const express = require('express')const app = express()const cors = require('cors')app.use(cors())//引入JSONPapp.get('/api/JSONP',(req,res)=>{//得到函数名称const funcName = req.query.callback//定义数据对象const data = {name:'lin',age:20}//拼接出一个函数的调用const scriptstr = `${funcName}(${JSON.stringify(data)})`res.send(scriptstr)})//配置CORS//const cors = require('cors')//app.use(cors())const router = require('./apiRouter')app.use('/api',router)app.listen(80,()=>{console.log("服务器启动")})

路由

const express = require('express')const appRouter = express.Router()appRouter.get('/get',(req,res)=>{//通过res.query获取客户端数据const query = req.query//这个方法提取对象console.log("返回数据"+query.name)res.send({ status:0, data:query})})appRouter.post('/post',(req,res)=>{//通过res.query获取客户端数据const body = req.query//这个方法提取对象console.log(body)res.send({ status:0, data:body})})appRouter.delete('/delete',(req,res)=>{//通过res.query获取客户端数据const body = req.query//这个方法提取对象console.log(body)res.send({ status:0, data:body})})appRouter.get('/jsonp',(req,res)=>{const funName = req.query.callbackconst data = {name:'zs',age:20}const scriptStr = `${funName}(${JSON.stringify(data)})`res.send(scriptStr)})module.exports = appRouter

页面

<!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='/jquery-3.2.1.min.js'></script></head><body><button id="get">Get</button><button id="post">Post</button><button id="delete">delete</button><button id="jsonp">jsonp</button><script>//测试get接口$(function(){$('#get').on('click',function(){$.ajax({type:'get',url:'http://localhost:80/api/get',data:{name:'lin',age:20},success:function(res){console.log(res)}})})//测试post接口$('#post').on('click',function(){$.ajax({type:'post',url:'http://localhost:80/api/post',data:{name:'long',age:20},success:function(res){console.log(res)}})})//测试post接口$('#delete').on('click',function(){$.ajax({type:'delete',url:'http://localhost:80/api/delete',data:{name:'long',age:20},success:function(res){console.log(res)}})})//测试JSONP测试点击事件$('#jsonp').on('click',function(){$.ajax({type:'get',url:'http://localhost:80/api/jsonp',dataType:'jsonp',success:function(res){console.log(res)}})})})</script></body></html>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。