nuxt通过Nginx简单配置转发,实现axios跨域

…衆ロ難τιáo~ 提交于 2020-01-18 16:24:01

跨域是前端开发中经常会遇到的问题,前端调用后台服务时,通常会遇到 No ‘Access-Control-Allow-Origin’ header is present on the requested resource的错误,这是因为浏览器的同源策略拒绝了我们的请求。

所谓同源是指,域名(包含二级域名),协议(http/https),端口相同,浏览器执行一个脚本时同源的脚本才会被执行。如果非同源,那么在请求数据时,浏览器会在控制台中报一个异常,提示拒绝访问。

一下是演示项目
demo
|----api.js
|----index.js
两个文件同级

// api.js
const server = require('express')()
var bodyParser = require('body-parser')
server.use(bodyParser())

server.get('/api/a', (req, res) => {
  // 服务器设置可以跨域
  // res.header('Access-Control-Allow-Origin', '*')
  // res.header('Access-Control-Allow-Headers', 'X-Requested-With')
  // res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
  // res.header('X-Powered-By', ' 3.2.1')
  // // 这段仅仅为了方便返回json而已
  // res.header('Content-Type', 'application/json;charset=utf-8')
  let a = {
    json: 1
  }
  res.json(a)
})
server.listen(8080, function () {
  console.log('server start')
})

index.js

const server = require('express')()
// 所有的get请求
server.get('*', (req, res) => {
  res.end(`
  <!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
  </head>
  <body>
  index.js
  </body>
  </html>
  <script>
  $.ajax({
    url:'http://localhost:8081/api/a',
    type: 'get',
    data:{
      "lang": 'en',
      "region": 'AE',
      "token": 'ghklnorstuyzIJMNPSTUVWXZ0123467915072',
      "currency_code": 'AED',
    },
    successs:function(res){
      console.log(res)
    }
  })
  </script>
    `)
})
server.listen(8081, function () {
  console.log('server start at: http://localhost:8081/')
})

现在终端(cmd)里输入

$ node api.js

然后打开链接

http://localhost:8080/api/a

会看到

{"json":1}

这里是通过api.js起一个node服务,相当于一个get接口,接口地址就是http://localhost:8080/api/a,
直接打开说明接口没问题,现在我们在终端(cmd)里输入

$ node index.js

起另一个web服务,这里端口不同,我们访问
http://localhost:8081/
看到一个跨域的错误

解决前端跨域

修改nginx.conf文件如下:

    # srever模块配置是http模块中的一个子模块,用来定义一个虚拟访问主机
    server {
        listen       8081; # 监听80端口
        server_name  localhost;
        # 根路径指到index.html
        location / {
            root   html;
            index  index.html index.htm;
        }
		
        # localhost/api 的请求会被转发到192.168.0.103:8080
        location /api {
           # rewrite ^/b/(.*)$ /$1 break; # 去除本地接口/api前缀, 否则会出现404
           # proxy_set_header Host $host;
           # proxy_set_header X-Real-IP $remote_addr;
           # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://localhost:8080; # 转发地址
			
	        #   指定允许跨域的方法,*代表所有
	        add_header Access-Control-Allow-Methods *;
	        #   预检命令的缓存,如果不缓存每次会发送两次请求
	        add_header Access-Control-Max-Age 3600;
	        #   带cookie请求需要加上这个字段,并设置为true
	        add_header Access-Control-Allow-Credentials true;
	        #   表示允许这个域跨域调用(客户端发送请求的域名和端口) 
	        #   $http_origin动态获取请求客户端请求的域   不用*的原因是带cookie的请求不支持*号
	        add_header Access-Control-Allow-Origin $http_origin;
	        #   表示请求头的字段 动态获取
	        add_header Access-Control-Allow-Headers 
	        $http_access_control_request_headers;
	        #   OPTIONS预检命令,预检命令通过时才发送请求
	        #   检查请求的类型是不是预检命令
	        if ($request_method = OPTIONS){
	            return 200;
	        }
        }
        # 重定向错误页面到/50x.html
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

nginx -s reload 重新载入nginx配置.再次访问http://localhost:8081/,就可以跨域访问了
nginx转发了,所有地址是localhost,端口是8081,的请求,都会被转发到http://localhost:8080去。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!