简体   繁体   English

cURL有效,但XMLHttpRequest没有?

[英]cURL works but XMLHttpRequest does not?

Making this call from terminal works: 从终端进行此呼叫:

curl -d "username=test&password=test" -X POST http://127.0.0.1:5000/login/

But from my Chrome Extension, an Ajax call fails with status 0. I've tried a number of things but haven't had any luck. 但是从我的Chrome扩展程序中,Ajax调用失败,状态为0.我尝试过很多东西,但没有运气。

function doLogin() {
    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;
    var params = 'username=' + username + '&password=' + password;

    sendPostRequest("http://127.0.0.1:5000/login/", params);
}

function sendPostRequest(url, params) {
    var http = new XMLHttpRequest();
    http.open('POST', url, true);
    http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    http.onreadystatechange = function () {
        // This is never called
        if (this.readyState == 4 && this.status == 200) {
            alert(http.status);
        }
    };

    http.send(params);
}

Server-side: 服务器端:

@app.route("/login/", methods=['POST'])
def login():
    username = request.form["username"]
    password = request.form["password"]

    auth = authenticate(username, password)

    return jsonify({'authentication': auth}), 200

I would appreciate feedback. 我很感激反馈。

I have recreated the scenario. 我重新创建了这个场景。 If you want to access the login route from outside of the templates folder, you need to allow CORS . 如果要从templates文件夹外部访问login路由,则需要允许CORS

I have installed flask-cors and allowed all origins. 我已经安装了flask-cors并允许所有来源。 You may change this to specific login route if necessary. 如有必要,您可以将其更改为特定的login路由。 Documentation of the package can be found in this documentation link . 可以在本文档链接中找到该软件包的文档

Folder structure: 文件夹结构:

├── app.py
├── extension.html
└── requirements.txt

requirements.txt : requirements.txt

Click==7.0
Flask==1.0.2
Flask-Cors==3.0.7
itsdangerous==1.1.0
Jinja2==2.10.1
MarkupSafe==1.1.1
pkg-resources==0.0.0
six==1.12.0
Werkzeug==0.15.2

app.py : app.py

from flask import Flask, request, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

def authenticate(username, password):
    if username == "test" and password == "test":
        return True
    return False

@app.route("/login/", methods=['POST'])
def login():
    username = request.form["username"]
    password = request.form["password"]
    auth = authenticate(username, password)
    return jsonify({'authentication': auth}), 200

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

extension.html : extension.html

<html>
<head>
  <title>Chrome Extension Login</title>
</head>
<body>
  <div>
    Username: <input type="text" id="username" /> <br>
    Password: <input type="text" id="password" /> <br>
    <button id="login_button">Login</button>
  </div>
  <script type="text/javascript">
  function doLogin() {
    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;
    var params = 'username=' + username + '&password=' + password;
    sendPostRequest("http://127.0.0.1:5000/login/", params);
  }
  function sendPostRequest(url, params) {
    var http = new XMLHttpRequest();
    http.open('POST', url, true);
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
        console.log(this.status);
        console.log(this.responseText);
      }
    };
    http.send(params);
  }
  var login_button = document.getElementById("login_button");
  login_button.addEventListener("click", doLogin);
  </script>
</body>
</html>

Output: 输出:

CURL request: CURL请求:

卷曲请求示例

Successful login with correct credentials: 使用正确的凭据成功登录:

成功登录

Error in login with wrong credentials: 使用错误凭据登录时出错:

登录时出错

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

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