【问题标题】:HTTP request blocked by CORS for not having Access-Control-Allow-Origin header but the header is present由于没有 Access-Control-Allow-Origin 标头但标头存在而被 CORS 阻止的 HTTP 请求
【发布时间】:2019-08-27 23:22:26
【问题描述】:

我正在使用 Python 和 Flask 并创建了一个 REST api,我需要我的 Vue 应用程序与之交互并获取数据,但我得到 No 'Access-Control-Allow-Origin' header is present。

我正在从 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

【问题讨论】:

    标签: python nginx vue.js flask vue-resource


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2015-10-01
      • 2021-02-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-09
      • 2016-12-21
      • 2016-04-02
      • 1970-01-01
      相关资源
      最近更新 更多