当前位置:网站首页>NodeJs - cross domain
NodeJs - cross domain
2022-08-03 15:16:00 【H5_ljy】
一、什么是跨域?
The cross-origin problem is due to the browser's same-origin policy restrictions.
什么是浏览器的同源策略:
浏览器的一种安全策略: 指 A protocol for two URLsip:port(端口) 三者一样代表同源
浏览器为了用户的信息安全,网页中有一个网络请求技术:AJAX 在网络请求时;请求的网址和当前页面的网址不是同一台服务器,It will be rejected to accept the data sent by the server.也就是ajaxThe request will have this cross-domain problem
比如:
二、解决跨域
1.CORS(跨域资源共享)技术
在数据包的头部配置Access-Control-Allow-Origin字段以后,数据包发送给浏览器后
浏览器就会根据这里配置的白名单 “放行” 允许白名单的服务器对应的网页来用ajax跨域访问
注意:跨域请求时,The frontend is the backend that requests cross-origin,It's just that the returned data is rejected by the browser,It is not that network requests are not sent across domains
方法一:directly on its own serverjs文件设置
res.setHeader("Access-Control-Allow-Origin","*") //The second parameter represents all access to this data,You can also set the server address to specify who can access it
res.end('{"name":"ljy",age:22}')
案例: when i want to visit8080端口的数据
//这是在8081端口打开的html文件
<button onclick="fn()">Click to request Baidu homepage</button>
<script>
function fn(){
let xhr=new XMLHttpRequest()||new ActiveXObject("Microsoft.XMLHTTP")
xhr.open("GET","http://localhost:8080/ajax1",true)
xhr.send()
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
console.log(xhr.responseText)
}
}
}
这是8080端口服务器js文件
var http = require("http")
http.createServer((req, res) => {
if (req.url=="/ajax1") {
res.setHeader("Access-Control-Allow-Origin", "*")
res.end('{"name":"ljy",age:22}')
}
}).listen(8080)

You can see that when we click the button, the request is made8080端口的数据
2.JSONP
前端网页中用ajax请求跨域服务器的网址 ,会报跨域错误
用script标签的srcattribute to request a URL from a cross-origin server will not report a cross-origin error,But it will directly use the requested encodingv8引擎去运行,So we need to wrap the function throughdomAction to add the requested data to the web page.
1.在后端写一个js引擎能识别的字符串发送给前端,这个字符串是这样的:’ fn({“name”:“ljy”}) ’
2.前端直接通过script标签的src属性去请求这个网址,请求完毕以后 v8It will directly run the code to callfn函数,So this function must be created in advance,Then put it in the business function to be executed and wait to be called.
3.函数的名称问题: 前端可以通过querystring把函数名以参数的形式发送给后端,After parsing the backend, it is directly spliced into the data,然后发送给前端.
4.通过dom操作创建scriptnode and set it upsrc属性去请求这个网址,然后将script标签添加到页面上.
First set on the server side of the request I am using this machine8080The port serves as the server side of the request,8081The port serves as the front-end server.
//8080服务器端
var http = require("http")
var url=require("url")
http.createServer((req, res) => {
var pathname=url.parse(req.url).pathname
if (pathname=="/car") {
let querystr=url.parse(req.url,true).query.callback //Accepts the function name sent by the frontend
var obj={"name":"ljy",age:22}
var jsonstr=JSON.stringify(obj)
res.end(`${querystr}(${jsonstr})`)
}
}).listen(8080)
//8081服务器前端
<button onclick="myload()">点击请求8080端口</button>
<script>
function myload(){
let myname="ljy"+new Date().getTime()
window[myname]=function(data){
console.log(data)
}
let myscript=document.createElement("script")
myscript.src=`http://localhost:8080/car?callback=${myname}`
document.body.append(myscript)
}

3.Proxy代理
在开发阶段 最常用的手段,比如Vue,React,Other front-end frameworks often have their own development server ,If a user visits ourA服务器的网页,inside the pageAJAX 去请求AThe data interface of the server,will not be cross-domain,然后A服务器去请求B服务器的数据,Then return toA服务器的数据 返回给用户.在这里AThe server is a proxy server
Here we use the backendrequestmodule to send the request.This is a third-party module that needs to be downloaded manually
1.安装request模块
npm i request
2.使用request模块
var http = require("http")
var url=require("url")
var request=require("request") //引入request模块
http.createServer((req, res) => {
var pathname=url.parse(req.url).pathname
if (pathname=="/car") {
request("http://localhost:8081/home.html",(arg1,arg2,arg3)=>{
res.end(arg3) //The first parameter is the requested URL,第二个参数为回调函数
})
}
}).listen(8080)
localhost:8081/home.html文件如下

边栏推荐
猜你喜欢

2021年12月电子学会图形化三级编程题解析含答案:数星星

高性能创作本,日常修图剪辑选华硕无畏Pro15 2022完全足矣!

cmd 关闭端口

每日练习------有10个数字要求分别用选择法从大到小输出

eolink告诉你,国内Api行业,可以内卷到什么程度?

The general trend, another key industry related to Sino-US competition, has reached a critical moment

深度学习——安装CUDA以及CUDNN实现tensorflow的GPU运行

R7 6800H+RTX3050+120Hz 2.8K OLED屏,无畏Pro15 2022开启预售

一次做数据报表的踩坑经历,让我领略了数据同步增量和全量的区别

QT之Mysql驱动
随机推荐
问题8:对朋友圈进行用例设计
今日睡眠质量记录75分
Currency ATM: Solana Wallet Has Unknown Security Vulnerability, A Large Number Of Users' Digital Assets Are Stolen
PAT乙级-B1014 福尔摩斯的约会(20)
liunx服务器遇到SYN_SENT洪水攻击
苹果开发「AI 建筑师」GAUDI:根据文本生成超逼真 3D 场景!
Mysql 生成排序序号
eolink告诉你,国内Api行业,可以内卷到什么程度?
教你如何获取微信公众号历史文章链接
mysql占用服务器CPU100%的解决办法
2021年12月电子学会图形化四级编程题解析含答案:新冠疫苗接种系统
js数组方法总结
【FPGA教程案例44】图像案例4——基于FPGA的图像中值滤波verilog实现,通过MATLAB进行辅助验证
方舟开服教程win
南京一研究所回应招聘硕士保安:负责安全生产等,48人选1
[The Beauty of Software Engineering - Column Notes] 36 | What exactly do DevOps engineers do?
leetcode-105 从前序与中序遍历序列构造二叉树-使用栈代替递归
上亿数据怎么玩深度分页?兼容MySQL + ES + MongoDB
devops-2:Jenkins的使用及Pipeline语法讲解
王守创:多组学整合分析揭示植物代谢多样性的分子机制(8月2号晚)