当前位置:网站首页>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月电子学会图形化二级编程题解析含答案:绘制多边形
DeepLink在转转的实践
2021年12月电子学会图形化一级编程题解析含答案:放学
每日练习------有10个数字要求分别用选择法从大到小输出
Internship Road: Documenting Confusion in My First Internship Project
问题5:发现缺陷怎么办?缺陷的类型有哪些?
eolink告诉你,国内Api行业,可以内卷到什么程度?
A high-performance creation book, ASUS Dreadnought Pro15 2022 is completely enough for daily photo editing and editing!
彻底搞懂云桌面配置及实践踩坑【华为云至简致远】
指令重排以及案例
随机推荐
一文搞懂$_POST和php://input的区别
R7 6800H+RTX3050+120Hz 2.8K OLED screen, Intrepid Pro15 2022 pre-sale
PAT乙级-B1018 锤子剪刀布(20)
程序员面试必备PHP基础面试题 – 第十八天
分布式系统与微服务的区别
php中接口、抽象类以及接口和抽象类区别详解
2021年12月电子学会图形化三级编程题解析含答案:跳高比赛
Clickhouse Filling the Pit 3: Left Join changed to Right Join, resulting in incorrect statistical results
NFT盲盒挖矿DAO智能合约dapp系统开发详情
PAT乙级-B1013 数素数(20)
2021年12月电子学会图形化三级编程题解析含答案:数星星
简单理解try catch和try finally
Currency ATM: Solana Wallet Has Unknown Security Vulnerability, A Large Number Of Users' Digital Assets Are Stolen
SQL 不新增表 把一张表定义成两张
【周报】2022年7月24日
兆骑科创创业大赛,双创服务平台,线上直播路演
跨桌面端之组件化实践
Detailed explanation of cloud hard disk EVS and how to use and avoid pits [HUAWEI CLOUD is simple and far]
PAT乙级-B1010 一元多项式求导(25)
HDU Largest prime factor(埃拉托色尼筛选法求素数模板法改动)