当前位置:网站首页>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月电子学会图形化四级编程题解析含答案:质数判断器
- MySQL中的基数是啥?
- 程序员面试必备PHP基础面试题 – 第二十一天
- leetcode-105 从前序与中序遍历序列构造二叉树-使用栈代替递归
- 网络中的交换机和路由器
- HDU 1406 (完数)
- 2021年12月电子学会图形化三级编程题解析含答案:跳高比赛
- How to use binary search and find whether the rotation in the array contains a (target) value?Rotate the sorted array leetcode 81. Search
- Detailed explanation of cloud hard disk EVS and how to use and avoid pits [HUAWEI CLOUD is simple and far]
- 身为程序员的我们如何卷死别人?破局重生。
猜你喜欢
随机推荐
WMS软件国内主要供应商分析
兆骑科创创业大赛,双创服务平台,线上直播路演
【软件工程之美 - 专栏笔记】36 | DevOps工程师到底要做什么事情?
取消转义字符(r)
Detailed explanation of cloud hard disk EVS and how to use and avoid pits [HUAWEI CLOUD is simple and far]
SwiftUI SQLite教程之了解如何在 SwiftUI 中使用 SQLite 数据库并执行 CRUD 操作(教程含源码)
liunx服务器遇到SYN_SENT洪水攻击
程序员面试必备PHP基础面试题 – 第十八天
正则表达式入门一
Currency ATM: Solana Wallet Has Unknown Security Vulnerability, A Large Number Of Users' Digital Assets Are Stolen
0 code 4 steps to experience IoT devices on the cloud
一次做数据报表的踩坑经历,让我领略了数据同步增量和全量的区别
你没见过的《老友记》镜头,AI给补出来了|ECCV 2022
2021年12月电子学会图形化三级编程题解析含答案:数星星
devops-2:Jenkins的使用及Pipeline语法讲解
Taurus.MVC WebAPI 入门开发教程1:框架下载环境配置与运行(含系列目录)。
PAT乙级-B1010 一元多项式求导(25)
HDU Largest prime factor(埃拉托色尼筛选法求素数模板法改动)
一个在浏览器中看到的透视Cell实现
2021年12月电子学会图形化四级编程题解析含答案:新冠疫苗接种系统









