你如何使用vue js向Flask后端api发布请求?

时间:2017-06-08 07:40:56

标签: javascript python flask vue.js backend

我正在尝试使用vue js和flask后端进行简单的注册过程。 但我收到此错误消息。

XMLHttpRequest无法加载http://localhost:5000/users。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许原点“http://localhost:8080”访问。

为什么会这样?

我的vue js代码正在关注

methods: {

    signup() {

        this.$http.post("http://localhost:5000/users", this.user)
            .then(function(data) {
                alert(data)
            })
    }

}

我的烧瓶后端代码正在关注

@app.route('/users', methods=['POST'])
    def users():
    username = request.form.get('username')
    password1 = request.form.get('password1')
    password2 = request.form.get('password2')
    first_name = request.form.get('first_name')
    last_name = request.form.get('last_name')
    email = request.form.get('email')

    file = request.files['avatar']

    if file.filename:
        if allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], 
    filename))
        else:
            error = "Your avatar has be to an image file"
            redirect(url_for('signup'))
    else:
        filename = ""


    if password1 == password2:
        user = User(username = username, password = password1, first_name = first_name, last_name = last_name,  email = email)
        user.save_to_db()

2 个答案:

答案 0 :(得分:1)

如果您都在本地托管它们,则可以尝试运行网络浏览器,例如没有网络安全性的Chrom在Windows的CLI中使用以下代码。希望对您有所帮助!

chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

答案 1 :(得分:0)

当您的API位于http://localhost:8080/时,您正在通过http://localhost:5000为您的应用提供服务,这两个来源是浏览器的不同来源!

来自MDN

  

资源在从不同的域,协议或端口请求资源时,会生成跨源HTTP请求。例如,http://domain-a.com提供的HTML页面会为http://domain-b.com/image.jpg

发出src请求      

对于安全原因,浏览器限制从脚本中发起的跨源HTTP请求。例如,XMLHttpRequest和Fetch遵循同源策略。因此,使用XMLHttpRequest或Fetch的Web应用程序只能向其自己的域发出HTTP请求。

     

跨域资源共享(CORS)机制为Web服务器提供跨域访问控制,从而实现安全的跨域数据传输。现代浏览器在API容器中使用CORS(例如XMLHttpRequest或Fetch)来降低跨源HTTP请求的风险。

在您的情况下,使用flask-cors或在与您的应用相同的域中托管您的API。