当前位置:网站首页>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文件如下
边栏推荐
猜你喜欢
方舟开服教程win
网络中的交换机和路由器
2021年12月电子学会图形化二级编程题解析含答案:绘制多边形
问题5:发现缺陷怎么办?缺陷的类型有哪些?
方舟生存进化开服需要多少钱
跨桌面端之组件化实践
Detailed explanation of cloud hard disk EVS and how to use and avoid pits [HUAWEI CLOUD is simple and far]
Currency ATM: Solana Wallet Has Unknown Security Vulnerability, A Large Number Of Users' Digital Assets Are Stolen
2021年12月电子学会图形化二级编程题解析含答案:消灭蝙蝠
方舟开服工具、服务器教程win
随机推荐
程序员面试必备PHP基础面试题 – 第十八天
手摸手带你完成智慧路灯构建及避坑【华为云至简致远】
web漏洞之远程命令/代码执行
MySQL性能优化的'4工具+10技巧'
跨桌面端之组件化实践
你没见过的《老友记》镜头,AI给补出来了|ECCV 2022
【周报】2022年7月31日
高性能创作本,日常修图剪辑选华硕无畏Pro15 2022完全足矣!
正则表达式入门一
Currency ATM: Solana Wallet Has Unknown Security Vulnerability, A Large Number Of Users' Digital Assets Are Stolen
地球自转加快
js数组方法总结
NFT盲盒挖矿DAO智能合约dapp系统开发详情
问题3:你提交的缺陷开发认为这不是BUG,怎么办?
问题4:什么是缺陷?你们公司缺陷的优先级是怎样划分的?
FATFS | 中文显示 | 长文件名
6000 字+,帮你搞懂互联网架构演变历程!
redis的使用方法
Taurus.MVC WebAPI 入门开发教程1:框架下载环境配置与运行(含系列目录)。
正则表达式入门二(普通字符)