当前位置:网站首页>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文件如下

边栏推荐
猜你喜欢
随机推荐
JS手写call apply bind (详细)(面试)
交大医学院临床研究中心如何将 ModelWhale 应用于临床医生教学、研究丨数据科学 x 临床医学
Currency ATM: Solana Wallet Has Unknown Security Vulnerability, A Large Number Of Users' Digital Assets Are Stolen
一文搞懂$_POST和php://input的区别
问题5:发现缺陷怎么办?缺陷的类型有哪些?
PAT乙级-B1016 部分A+B(15)
DeepLink在转转的实践
MMA安装及使用优化
方舟开服工具、服务器教程win
HDU 1027 Ignatius and the Princess II(求由1-n组成按字典序排序的第m个序列)
正则表达式入门二(普通字符)
夜神浏览器fiddler抓包
sql注入之盲注(纯原创)
SQL 不新增表 把一张表定义成两张
测试基础整合-测试分类、软件质量模型、测试流程、测试用例、测试点划分方法、缺陷、例子
简单理解try catch和try finally
SwiftUI SQLite教程之了解如何在 SwiftUI 中使用 SQLite 数据库并执行 CRUD 操作(教程含源码)
上亿数据怎么玩深度分页?兼容MySQL + ES + MongoDB
跨桌面端之组件化实践
ffplay视频播放原理分析








