nginx创建本地服务器和配置代理(解决跨域)

1,下载nginx

2,解压后打开conf/nginx.conf 修改配置

server {         
        listen        8841;#监听端口    
        server_name  localhost;#代理服务地址
        location / { #默认访问
            root  html; 
            index  index.html index.php 1.php 1.html;
        }
        #开始配置我们的反向代理
        location /api{        #"/api"中的api可以替换为自定义的任何内容     
            rewrite ^/api/(.*)$ /$1 break;     
            include uwsgi_params;     
            proxy_pass https://api.ioser.net; #我们要反向代理的地址,这里以本地的tomcat服务器为例  
            charset utf-8;   #显示中文      
            add_header 'Access-Control-Allow-Origin' '*'; #允许来自所有的访问地址           
            add_header 'Access-Control-Allow-Credentials' 'true';       
            add_header 'Access-Control-Allow-Methods' 'GET, PUT, POST, DELETE, OPTIONS'; #支持请求方式            
            add_header 'Access-Control-Allow-Headers' 'Content-Type,*';  
        }
    }

 3,请求数据的时候用localhost:8841(监听的端口号)代理需要请求数据的地址,例如:

var url1 = "http://localhost:8841/api/api/get_phone_info?access_token=UQbC9X4iqAt7YXfli9IELpogAr2KjkLx&phone=18824678858";
            fetch(url1).then(res=>{
                return res.json()
            }).then(data=>{
                console.log(data)
            })

然后在对应监听的接口打开html文件,里面既可写代码(http://localhost:8841/index.html)

二。创建本地服务器

在nginx 目录下输入命令:

npm install express

安装 express模块,

2,在跟目录下新建一个server.js,写入代码即可

const express = require('express')
const app = express()
const port = 9000

app.get('/', (req, res) => {
  res.send({
      code:200,
      msg:"请求成功",
      data:{
          text:"123"
      }
      
  })
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

send 里面就是服务器返回的数据

3,使用命令

node server.js

开启服务器即可

 

posted @ 2021-04-25 17:29  吴百万  阅读(1705)  评论(0编辑  收藏  举报