当前位置:网站首页>1-19 利用CORS解决接口跨域问题
1-19 利用CORS解决接口跨域问题
2022-06-30 21:26:00 【画不完的饼】
利用CORS解决接口跨域问题
GET和POST接口,存在一个很严重的问题:不支持跨域的请求。
解决接口跨域问题的方案主要有两种:
- CORS(主流的解决方案,推荐使用)
cors是Express的一个第三方中间件。通过安装和配置cors中间件,可以很方便地解决跨域问题。
使用的步骤分为如下三步:
1.运行 npm install cors 安装中间件
2.使用const cores = require(‘cors’) 导入中间件
3.在路由之前调用app.use(cors())配置中间件
什么是CORS跨域资源共享?
COR(cross-Origin Resource Sharing,跨域资源共享)由一系列HTTP响应头组成,这些HTTP响应头决定浏览器是否阻止前端JS代码跨域获取资源。
浏览器的同源安全策略默认会阻止网页“跨域”获取资源。但如果接口服务器配置了CORS相关的HTTP响应头,就可以接触浏览器端的跨域访问限制。
(1)CORS响应头部可以携带一个Access-Control-Allow-Origin
如果制定了Access-Control-Allow-Origin字段的值为通配符*,表示允许来自任何域的请求,示例代码如下:
res.setHeader('Access-Control-Allow-Origin','*')
(2)默认情况下,CORS仅支持客户端向服务器发送如下的9个请求头:
Accept、Accept-Language、Content-Language、DPR、Downlink、Save-Data、Viewport-Width、Width、Content-Type(值仅限于text/plain、mutipart、from-data、application/x-www-form-urlencoded三者之一)
如果客户端向服务器发送了额外的请求头信息,则需要在服务器端,通过Access-Control-Allow-Headers 对额外的请求头进行声明,否则这次请求会失败
(3)响应头Access-Control-Allow-Methods
默认情况下,CORS仅支持客户端发起GET、POST、HEAD请求。
如果客户端希望通过PUT、DELETE等方式请求服务器的资源,则需要在服务器端,通过Access-Control-Alow-Methods来指明实际请求所允许使用的HTTP方法。
//默认只支持POST,GET,DELETE请求方法
//只允许POST,GET,DELETEM,HEAD请求方式
res.setHeader('Access-Control-Alow-Methods','POST,GET,DELETEM,HEAD')
//允许所有的HTTP请求方法
res.setHeader('Access-Control-Alow-Methods','POST,GET,DELETEM,HEAD')
const cors = require('cors')
app.use(cors())
- JSONP(有缺陷的解决方案:只支持GET请求)
边栏推荐
猜你喜欢

ArcMap|用字段计算器对不同类别的id赋值

Spatiotemporal data mining: an overview

Et la dégradation du modèle de génération de texte? Simctg vous donne la réponse

Apply for vector bus protocol color picture wallpaper hanging picture, very good!
Understand what MySQL index push down (ICP) is in one article

pytorch geometric torch-scatter和torch-sparse安装报错问题解决

Clickhouse Native Monitoring item, System table Description

Markdown notes concise tutorial

SQL server extracts pure numbers from strings
笔记【JUC包以及Future介绍】
随机推荐
双立体柱状图/双y轴
Clickhouse Native Monitoring item, System table Description
开发技术-使用easyexcel导入文件(简单示例)
asp. Net core JWT delivery
Personal developed penetration testing tool Satania
两个skyline
个人开发的渗透测试工具Satania
毕业五年,想当初若没有入行测试,我是否还会如这般焦虑
利用日志服务器输出各种apache的日志的TOPN
Reading notes of Clickhouse principle analysis and Application Practice (1)
Adobe-Photoshop(PS)-脚本开发-去除文件臃肿脚本
Why have the intelligent investment advisory products collectively taken off the shelves of banks become "chicken ribs"?
asp.net core JWT传递
雷达数据处理技术
ceshi deces
twelve thousand three hundred and forty-five
Clickhouse distributed table engine
对多态的理解
The 16th Heilongjiang Provincial Collegiate Programming Contest
Markdown笔记简明教程