cURL有效,但XMLHttpRequest不起作用吗?

时间:2019-05-13 02:57:15

标签: javascript flask xmlhttprequest

从终端拨打此电话的工作方式:

$env:PsModulePath

但是从我的Chrome扩展程序中,Ajax呼叫失败,状态为0。我尝试了许多尝试,但没有任何运气。

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

服务器端:

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);
}

我希望能收到反馈。

1 个答案:

答案 0 :(得分:0)

我已经重新创建了场景。如果要从login文件夹之外访问templates路由,则需要允许CORS

我已经安装flask-cors并允许所有来源。如有必要,您可以将其更改为特定的login路由。该软件包的文档可以在in this documentation link中找到。

文件夹结构:

├── app.py
├── extension.html
└── 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

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

<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>

输出:

CURL请求:

curl request example

使用正确的凭据成功登录:

successful login

使用错误的凭据登录时出错:

error in login