[英]How can I send username and password to an express server with ajax?
This is the ajax method to send the form to server: 这是将表单发送到服务器的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);
}
});
});
The following is my index.js: 以下是我的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}');
});
But i'm only getting 'Error' and sometimes the server gets the POST and sometimes not, why and how can i fix this? 但是我只收到“错误”,有时服务器收到POST,有时没有,我为什么以及如何解决这个问题?
$(this).serialize()
should be referencing your form (eg, $('#my-form').serialize()
). $(this).serialize()
应该引用您的表单(例如$('#my-form').serialize()
)。
from https://api.jquery.com/serialize/ 来自https://api.jquery.com/serialize/
It can act on a jQuery object that has selected individual form controls, such as
<input>
,<textarea>
, and<select>
它可以作用于已选择单个表单控件的jQuery对象,例如
<input>
,<textarea>
和<select>
if that is indeed your form and you still have issues, what is the value of textStatus
and errorThrown
in the error callback? 如果那确实是您的表单并且仍然存在问题,那么错误回调中的
textStatus
和errorThrown
的值是什么? does the request reach the console.log('Login request')
statement? 请求是否到达
console.log('Login request')
语句?
the following express code works for me: 以下快速代码对我有用:
...
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)
})
...
with the following AJAX code: 使用以下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)
}
})
EDIT added sample express & ajax code 编辑添加了示例Express和Ajax代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.