@vue-cli 3.x + CORS 跳过跨域检查的设置

 #package.json 相关版本
 "vue": "^2.6.10", 
 "@vue/cli-plugin-babel": "^3.11.0",
 "@vue/cli-plugin-unit-mocha": "^3.11.0",
 "@vue/cli-service": "^3.11.0",
 "@vue/test-utils": "1.0.0-beta.29",

背景故事:

本机同时开发前端和后端,后端python -> web.py, 前端vuejs,  axios 封装的get/post

 

问题

当尝试post数据给web.py时,console里面收到下面的错误提示:

Access to XMLHttpRequest at 'https://192.168.31.66:10000/login' from origin 'http://192.168.31.66:8082' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

解决办法

注意: vue-cli不同版本之间,配置项的改动比较多,可以自行参考官方文档。

https://cli.vuejs.org/zh/config/#crossorigin

 

我这里修改如下:

1.  package.json同级目录里面创建了vue.config.js

2.  vue.config.js 内容如下:

// vue.config.js
module.exports = {
    crossorigin: 'anonymous'
}

3.  web.py对应的服务类里面,在返回数据前,添加了如下header信息:

import web
import json

def buildCROSHeader():
    # dev only, add below header to bypass CROS policy
    web.header('Access-Control-Allow-Origin', '*')
    web.header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
    web.header('Access-Control-Allow-Headers',
               'x-requested-with,content-type')
    web.header('content-type', 'text/json')

class Login:

    def GET(self):
        buildCROSHeader()
        resp = {'status': 403,
                'success': False,
                'data': 'Not supported'}
        return json.dumps(resp)

    def POST(self):
        buildCROSHeader()
        i = web.input()
        verified = False;
        
        #logic to check username/password
        #assume this user passed the check;
        verified = True
        if verified:
            resp = {
                'status': 200,
                'success': True,
                'data': {'username': i.username, 'valid': True}
            }
            return json.dumps(resp)
        else:
            resp = {
                'status': 401,
                'success': False,
                'data': {'username': i.username, 'valid': False}
            }
            return json.dumps(resp)

 

如此这般改动后,从 http://localhost:8082   请求 https://localhost:10000/ 上面的东西,就正常了。

 

此方法只是用于开发使用,正规套路都是proxy

 

 

仅供参考。

 

 

你可能感兴趣的:(想当个全栈,vue,web.py)