繁体   English   中英

由于没有 Access-Control-Allow-Origin 标头但标头存在而被 CORS 阻止的 HTTP 请求

[英]HTTP request blocked by CORS for not having Access-Control-Allow-Origin header but the header is present

我在 Flask 中使用 Python 并创建了一个 REST api,我需要我的 Vue 应用程序与之交互并获取数据,但我没有出现“Access-Control-Allow-Origin”标头。

我正在添加来自 nginx 的标头(因此我可以代理 API,因为开发服务器没有任何允许跨域访问的选项)我尝试使用 jQuery 而不是 vue-resource 并且有效。

nginx配置:

server {
 listen 5089;
 access_log off;
 error_log /dev/null crit;
 location / {
     add_header 'Access-Control-Allow-Headers' 'content-type';
     add_header 'Access-Control-Allow-Origin' '*';
     proxy_pass http://localhost:5000;
     proxy_read_timeout  90;
 }
}

Vue 组件:

<template>
  <div id="app">
    <div id="nav">
      <router-link to="/" class="btn-dark">Home</router-link>
      |
      <router-link to="/about">About</router-link>
    </div>
    <label>User ID:
      <input type="text" v-model="auth.id" required/>
    </label>
    <label>
      Password:
      <input type="text" v-model="auth.password"/>
    </label>
    <button v-on:click.prevent="getToken">Submit</button>
  </div>
</template>
<script>
export default {
  data () {
    return {
      auth: {
        id: '',
        password: ''
      }
    }
  },
  methods: {
    getToken: function (token) {
      this.$http.post('http://localhost:5089/auth', {
        UID: this.auth.id,
        pass: this.auth.password
      }).then(function (data) {
        console.log(data)
      })
    }
  }
}
</script>

API路由代码:

@app.route('/auth', methods=['POST'])
def authenticate():
    print(request.form)
    for data in request.form:
        try:
            jsonParsed = json.loads(data)
            id = jsonParsed['UID']
            allegedPass = jsonParsed['pass']
        except Exception:
            return jsonify({
                'message': 'Oopsie Whoopsie what a nice cat, look'
            })
    if id and allegedPass:
        authFile = open('auth.json', 'r')
        authData = json.load(authFile)
        authFile.close()
        try:
            hashedPass = authData[str(id)]['pass']
        except Exception:
            return jsonify({
                'message': 'Oopsie Whoopsie look, a foxie'
            })
        if hashedPass == allegedPass:
            token = jwt.encode({'id': id, 'pass': allegedPass, 'exp': datetime.utcnow() + timedelta(minutes=15)},
                               app.config['secret'])
            return jsonify({
                'token': token.decode('UTF-8')
            })
        else:
            return jsonify({
                'message': 'GTFO'
            })
    else:
        return jsonify({
            'message': 'Kill yourself already.'
        })

它应该将令牌发送回应用程序,但我在控制台中收到以下错误:

POST http://localhost:5089/auth 500 (INTERNAL SERVER ERROR)
Access to XMLHttpRequest at 'http://localhost:5089/auth' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

在 API 终端上,我得到:

127.0.0.1 - - [06/Apr/2019 09:24:13] "OPTIONS /auth HTTP/1.0" 200 -
ImmutableMultiDict([])
127.0.0.1 - - [06/Apr/2019 09:24:13] "POST /auth HTTP/1.0" 500 -

Traceback (most recent call last):
.
.
.
File "/home/sids/Projects/laboratory/py/server.py", line 58, in authenticate
    if id and allegedPass:
UnboundLocalError: local variable 'id' referenced before assignment

结果是 vue-resource 模块没有正确发送数据或没有正确接收数据; 因此,当我尝试解析请求表单时,出现了导致问题的错误,并且浏览器假定 Origin 已被阻止,尽管不知道; 但是,我现在正在使用 jQuery; 那个有效

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM