Vue.js和Flask的CORS问题:阻止的XMLHttpRequest

2w2cym1i  于 2023-10-23  发布在  Vue.js
关注(0)|答案(3)|浏览(172)

产品描述:
我正在使用Vue.js构建一个Web应用程序,前端使用Flask。我从一个简单的登录页面开始。然而,当我从Vue.js应用程序向Flask后端发出请求时,我遇到了CORS(跨域资源共享)问题。
问题:
当我尝试从http://localhost:8081的Vue.js应用程序向http://localhost:5000的Flask服务器发出POST请求时,我收到以下错误:
CORS策略已阻止从源“http://localhost:8081”访问位于“http://localhost:5000/login”的XMLHttpRequest:对印前检查请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。
代码:
LoginForm.vue

<div>
    <h2>Login</h2>
    <form @submit.prevent="login">
      <div>
        <label for="username">Username:</label>
        <input type="text" id="username" v-model="username" />
      </div>
      <div>
        <label for="password">Password:</label>
        <input type="password" id="password" v-model="password" />
      </div>
      <button type="submit">Login</button>
    </form>
    <div>{{ message }}</div>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  data() {
    return {
      username: '',
      password: '',
      message: '',
    };
  },
  
  methods: {
    async login() {
      try {
        const response = await axios.post('http://localhost:5000/login', {
          username: this.username,
          password: this.password,
        });

        if (response.status === 200) {
          this.message = 'Login successful!';
        } else {
          this.message = 'Invalid credentials';
        }
      } catch (error) {
        console.error('An error occurred:', error);
      }
    }
  },
};
</script>

app.py

from flask import Flask, request, make_response, jsonify
from flask_cors import CORS, cross_origin
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
import os

app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "http://localhost:8081"}})

# Sample user data (for demo purposes)
users = [
    {"username": "user1", "password": "password1"},
    {"username": "user2", "password": "password2"},
]

SECRET_KEY = os.urandom(24)

def generate_user_token():
    serializer = Serializer(SECRET_KEY, expires_in=3600)

    token_data = {'is_admin': True}

    token = serializer.dumps(token_data).decode('utf-8')

    return token

@app.route('/login', methods=['POST'])
@cross_origin(origin="http://localhost:8081", supports_credentials=True)
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    for user in users:
        if user['username'] == username and user['password'] == password:
            if username == 'user1':
                token = generate_user_token()  
                return make_response(jsonify({'token': token}), 201)
            return jsonify({"message": "Login successful!"}), 200

    # Returns 403 if the password is wrong
    return make_response(
        'Could not verify',
        403,
        {'WWW-Authenticate': 'Basic realm="Wrong Password !!"'}
    )

if __name__ == '__main__':
    app.run(debug=True)

要求:
我将感谢任何关于如何解决此CORS问题并在我的Vue.js和Flask应用程序之间实现通信的指导。我是否应该采取任何其他步骤来确保正确的CORS配置?
我尝试过的:

  • 我已经安装了Flask-CORS并在我的Flask应用程序中配置了它。- 我在我的Flask路由中添加了必要的CORS头文件,包括EST-Control-Allow-Origin头文件。- 我已经确保我的Vue.js应用程序和Flask服务器在指定的端口上运行。
    尽管做出了这些努力,CORS问题仍然存在,我无法从Vue.js应用程序向Flask后端发出请求。
    Request Headers from Postman
    Response Header from Postman
wwtsj6pe

wwtsj6pe1#

我在flask应用程序中处理CORS,使用:

from flask_cors import CORS, cross_origin
CORS(app, support_credentials=True)

在路线中:

@app.route('/api/admin_login' , methods=['POST'])
@cross_origin(supports_credentials=True)
def admin_Login():
   # codes!

   # responses
   return make_response(jsonify({'token' : token.decode('UTF-8')}), 201)
    # returns 403 if password is wrong
    return make_response(
        'Could not verify',
        403,
        {'WWW-Authenticate' : 'Basic realm ="Wrong Password !!"'}
    )
xv8emn3q

xv8emn3q2#

我认为最好的解决办法是建立一个代理制度。转到vue项目根目录下的vue.config.js文件,如果它不存在,请创建一个。在其中,键入以下代码:

module.exports = {
  devServer: {
   proxy: {
    '^/api': {
      target: 'http://localhost:5000/',
      ws: true,
      changeOrigin: true
     },
   }
 }
}
v8wbuo2f

v8wbuo2f3#

当我像下面这样纠正代码时,它工作正常

这是我的请求

这是我的结果

下面是完整的代码

from flask import Flask, request, make_response, jsonify
from flask_cors import CORS, cross_origin
# This line will lead to below error so I correct TimedJSONWebSignatureSerializer to URLSafeTimedSerializer
# "ImportError: cannot import name 'TimedJSONWebSignatureSerializer' from 'itsdangerous'
from itsdangerous import URLSafeTimedSerializer as Serializer 
import os
import time

app = Flask(__name__)
# This line is no need so I commented
# CORS(app, resources={r"/*": {"origins": "http://localhost:8081"}})

# Sample user data (for demo purposes)
users = [
    {"username": "user1", "password": "password1"},
    {"username": "user2", "password": "password2"},
]

SECRET_KEY = os.urandom(24)

def generate_user_token():
    serializer = Serializer(SECRET_KEY)

    token_data = {'is_admin': True,'expire_time': time.time() + 3600}
    # Move expires_in to here
    token = serializer.dumps(token_data)

    return token

@app.route('/login', methods=['POST'])
@cross_origin(origin="*", supports_credentials=True)
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    for user in users:
        if user['username'] == username and user['password'] == password:
            if username == 'user1':
                token = generate_user_token()  
                return make_response(jsonify({'token': token}), 201)
            return jsonify({"message": "Login successful!"}), 200

    # Returns 403 if the password is wrong
    return make_response(
        'Could not verify',
        403,
        {'WWW-Authenticate': 'Basic realm="Wrong Password !!"'}
    )

if __name__ == '__main__':
    app.run(debug=True)

相关问题