使用nginx解决跨域问题---小实操

环境准备

前端
node+express访问html文件
1.首先在需要操作的文件夹下安装express模块

D:\vs code\File\hrml\mysqlweblod> npm install express

2.先写第一个web服务

创建app.js文件,如下

let express = require('express')
// 创建应用
let app = express()
 
// get请求
app.get('/user/find',(req,res)=>{
    res.send('hello')
})
 
// 启动服务,监听端口
app.listen(3000,()=>{
    console.log('启动成功...')
})

此时,可以开启node服务,
在当前文件目录终端下输入:node. app.js
在当前文件目录终端下输入:node.app.js
访问 http://localhost:3000/user/find 显示

Holle word

在这里插入图片描述

3.创建index.js文件,如下

//引入exprexx模块
var express =require("express");
var app =express();
app.use(express.static('public'))

//参数‘/’可当作设置url的根显示页面,这里即”http://localhost:8082/“访问的页面设置为index2.html
app.get('/',(req,res)=>{
    res.sendFile(__dirname+"/"+"index2.html")        //设置/ 下访问文件位置
});

//参数‘/index’可当作设置url的/index下显示页面,这里即”http://localhost:8082/index“访问的页面设置为index2.html
app.get("/index",(req,res)=>{
    res.sendFile(__dirname+"/"+"index.html")        //设置/index下访问文件位置
})

//设置端口8082访问地址,即http://localhost:8082
var server =app.listen(8082,()=>{
    var port =server.address().port
    console.log("【】访问地址http://localhost:%s",port)
})

准备index.html:

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<h2>Hello World!</h2>
<p>即将访问:localhost:3000/user/find</p>
<script type="text/javascript">
    function fun1(){
        var request = new XMLHttpRequest();
        request.open("GET","http://localhost:3000/user/find")
        request.send();
        request.onreadystatechange = function(){
            if(request.status==200 && request.readyState == 4){
                console.log("响应的结果" + request.responseText)
            }
        }
    }
</script>
</body>
    <input type="button" value="跨域调用" onclick="fun1()">
</html>

index2.html文件:

<meta charset="utf-8">
<p>我是index2</p>

此时,可以开启node服务,
在当前文件目录终端下输入:node. index.js
在这里插入图片描述
访问 http://localhost:8082/ 显示

我是index2

在这里插入图片描述
访问 http://localhost:8082/index 显示

在这里插入图片描述
此时点击按钮,会发生跨域问题:

在这里插入图片描述

此时跨域问题准备好了,我们准备解决方法。

Nginx配置

打开nginx.conf文件
修改配置:

server {
        listen       8000;
        server_name  localhost;
       # / 表示匹配路径为/的url
        location / {
           proxy_pass http://localhost:8082;
        }
 
        # /user 表示访问以/user 开头 的地址 如/username,/user/find等
        location /user {
           proxy_pass http://localhost:3000;
        }
 
    }

上面代码的意思是,

把访问localhost:8000 转换成访问 localhost:8082

而访问localhost:8000/user…则转换成localhost:3000/user

保存后,双击nginx.exe
在这里插入图片描述
(如果一闪而过,在任务管理器有nginx.exe就可以了,就算运行成功。)

在这里插入图片描述

修改访问地址

打开index.html文件

将
request.open("GET","http://localhost:3000/user/find")
改为
request.open("GET","http://localhost:8000/user/find")

此时已配置完成,已经解决了跨域问题了。

测试

打开http://localhost:8000/ ,访问的是 localhost:8082
在这里插入图片描述

打开http://localhost:8000/index ,访问的是localhost:8082/index
在这里插入图片描述
此时点击按钮,访问的是http://localhost:8000/user/find,其实访问的是http://localhost:3000/user/find

在这里插入图片描述

此时可以成功访问了!!!

参考:

node+express的html页面访问
一篇文章让你搞懂如何通过Nginx来解决跨域问题
nginx解决跨域问题

### Nginx 配置解决问题 为了使Nginx能够处理来自不同源的HTTP请求,即解决CORS(Cross-Origin Resource Sharing)问题,在Nginx配置文件中添加特定的响应头是必要的措施之一。对于`Access-Control-Allow-Origin`头部来说,可以通过如下方式来设置: #### 方法一:全局配置允许所有访问 如果目标是在开发环境中快速验证功能或是确实需要开放给任何来源站点访问资源,则可以在http、server或location上下文中加入以下指令[^1]。 ```nginx add_header Access-Control-Allow-Origin *; ``` 然而需要注意的是,这种做法存在安全隐患,因为它意味着所有的外部网站都可以无条件地向该服务发起请求并获取数据。 #### 方法二:指定单个或多个可信任的名 更安全的做法是指定具体的可信源站地址作为`Access-Control-Allow-Origin`的值。这可以有效防止未经授权的第三方网站滥用API接口。 ```nginx add_header Access-Control-Allow-Origin http://example.com; # 或者支持多名时使用正则表达式匹配 if ($http_origin ~* (http://|https://)(www\.)?(domain1\.com|domain2\.com)) { add_header Access-Control-Allow-Origin $http_origin; } ``` 除了上述基本配置外,有时还需要额外声明其他相关联的CORS头部信息以便更好地控制资源共享行为,比如允许哪些方法(`GET`, `POST`)以及自定义请求头字段等[^3]。 ```nginx add_header Access-Control-Allow-Methods "GET, POST, OPTIONS"; add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept"; ``` 特别注意针对预检请求(Preflight Request),也就是浏览器发送OPTIONS类型的探测性请求之前端会先询问服务器是否同意实际操作所携带的方法和headers组合;因此建议为这类特殊场景也做好相应准备。 最后提醒一点关于字体文件之类的静态资源,默认情况下它们不会自动带上这些CORS相关的头部信息,所以如果你的应用涉及到此类资产加载失败的情况,请记得单独为其路径下的资源加上合适的cross-origin属性或者调整Nginx配置以确保正常工作[^2]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值