使用nginx反向代理解决跨域

需要使用到的包
npm install express --save
npm install --save-dev http-proxy-middleware

以及对应的使用说明文档链接:
https://www.expressjs.com.cn/
https://www.npmjs.com/package/http-proxy-middleware

使用express创建一个本地服务器
默认为3000,可将其改成其他的端口,我这里使用的是9000端口

项目目录如下:
在这里插入图片描述

index.js如下:

// include dependencies
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
//app.get('/',(req,res)=>res.send('hello world'))
// proxy middleware options
const options = {
  target: 'https://www.xxx.com', // target host
  changeOrigin: true, // needed for virtual hosted sites
  ws: true, // proxy websockets
  pathRewrite: {
    /* '^/api/old-path': '/api/new-path', // rewrite path
    '^/api/remove/path': '/path', // remove base path */
    '^api':'',
  },
  /* router: {
    // when request.headers.host == 'dev.localhost:3000',
    // override target 'http://www.example.org' to 'http://localhost:8000'
    'dev.localhost:3000': 'http://localhost:8000',
  }, */
};
 
// create the proxy (without context)
const exampleProxy = createProxyMiddleware(options);
 
// mount `exampleProxy` in web server

app.use('/api', exampleProxy);
//使用express服务器托管静态文件,在目录创建一个public文件夹,并将index.html放入public
app.use(express.static('public'))
app.listen(9000);

index.html如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div onclick="aa()">
    hello world
    </div>
    <script>
        function aa(){
        	//使用fetch发送xhr请求
        	//这里是识别标志,我这里写/api作为识别,以后请求只需要/api,不需要再写全部
            fetch('/api/rand.tbimg.php?format=jpg').then(res=>{
                console.log('hi')
            })
        }
    </script>
</body>
</html>

在终端敲 node index.js 会出现如下提示,但并不影响最终的运行
在这里插入图片描述

运行结果如下:
在这里插入图片描述

解决了跨域问题
记得端口要输入localhost:9000/index.html
第一次访问 200
按F5刷新(第二次访问) 304
按Ctrl+F5强制刷新 200

还有一种方法是在nginx的安装包内修改conf的配置,如下图所示
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值