簡體   English   中英

如何使用Ajax將用戶名和密碼發送到快遞服務器?

[英]How can I send username and password to an express server with ajax?

這是將表單發送到服務器的ajax方法:

$("#submit").click( function() {

    $.ajax({
        url: '/login',
        type: "POST",
        dataType: "html",
        contentType: 'application/x-www-form-urlencoded',
        data: $('#submit-form').serialize(),
        username: $('#username').val(),
        password: $('#password').val(),
        beforeSend: function(xhr) {},
        success: function(data) {               
             console.log('Success');
        },
        error: function(jqXHR, textStatus, errorThrown) {
             // alert('error ' + textStatus + " " + errorThrown);
             console.log(this.data);
             console.log('Error', textStatus, errorThrown);
        }
    });

});

以下是我的index.js:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/login', function (req, res) {
    console.log('body=', req.body);
    res.end('{"success" : "Success", "status" : 200}');
});

但是我只收到“錯誤”,有時服務器收到POST,有時沒有,我為什么以及如何解決這個問題?

$(this).serialize()應該引用您的表單(例如$('#my-form').serialize() )。

來自https://api.jquery.com/serialize/

它可以作用於已選擇單個表單控件的jQuery對象,例如<input><textarea><select>

如果那確實是您的表單並且仍然存在問題,那么錯誤回調中的textStatuserrorThrown的值是什么? 請求是否到達console.log('Login request')語句?

以下快速代碼對我有用:

...
var app = express()
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))

app.post('/login', function (req, res) {
  console.log('body=', req.body)
})
...

使用以下AJAX代碼:

$.ajax({
  url: '/login',
  type: "POST",
  dataType: "html",
  data: $('#form').serialize(),
  contentType: 'application/x-www-form-urlencoded',
  username: $('#username').val(),
  password: $('#password').val(),
  beforeSend: function(xhr) {},
  success: function(data) {               
      console.log('Success');
  },
  error: function(jqXHR, textStatus, errorThrown) {
      // alert('error ' + textStatus + " " + errorThrown);
      console.log('Error', textStatus, errorThrown)
  }
})

編輯添加了示例Express和Ajax代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM