gpt4 book ai didi

javascript - Express POST - 返回的 JSON 被 JQuery 视为无效

转载 作者:搜寻专家 更新时间:2023-11-01 00:45:21 25 4
gpt4 key购买 nike

我正在尝试使用 Express 和 Node 编写一个小型身份验证服务。

我在 SO 上进行了搜索,但似乎没有找到我的答案即使有很多类似的问题,但没有真正确定的答案。

我尝试了服务器端代码的多种变体,但是看来我仍然缺少一些东西。

POST 调用是从 HTML 页面进行的使用一些 JQuery 代码(ajax 调用)。

我在 Express 中输入了 post() 方法,但是当它返回对 HTML 页面的响应,总是 ajax执行错误处理程序,从不执行成功处理程序。

我返回的 JSON 对我来说似乎有效。我尝试调用 send 和 json响应对象,但没有任何效果。

我错过了什么?

如有任何帮助,我们将不胜感激。提前致谢。

var mod = require('express');

var auth = require('./login_module.js'); // my module

var express = require('express');
var app = express();

app.use(express.bodyParser());

app.post('/login', function(request, response) {

console.log("post method called");

var credentials = request.body;
console.log("credentials = " + credentials);
console.log(credentials);

auth.authenticate(credentials.username, credentials.password, function(result){
console.log("Authentication Result: " + result);
var code = result === 1 ? 200 : 401;
console.log("Response Code: " + code);
var res = {
data : "Response Code: " + code
};
console.log(JSON.stringify(res));

// So far I am good!

response.statusCode = code;
response.json(res);

// Response is now sent
// but not recognized as
// valid JSON in the client.
console.log("response sent");
});

});

app.listen(10101);

JQuery 调用。

  <script type="text/javascript">
$(document).ready(function(){
$( "#btn" ).click(function(){
alert('calling now!');
var obj = {
username: $('#usrn').val(),
password: $('#pwd').val()
};
$.ajax({
type: "POST",
url: 'http://localhost:10101/login',
data: obj,
success: function (data, textStatus, jqXHR){
alert('got response back!');
if ("200" === textStatus){
$('#status').text('Login succeeded!');
}else if ("401" === textStatus){
$('#status').text('Login failed!');
}else{
$('#status').text('Invalid status received: ' + textStatus);
}
},
error : function(jqXHR, textStatus, errorThrown){
alert("Error when getting response.");
},

dataType: 'json'
});
})
});
</script>

最佳答案

正如 adeneo 指出的那样,关键是通过
提供 html 页面http 而不是通过文件协议(protocol)。剩下的只是一些调整
关于 Ajax jQuery 调用的各种细节。

服务器端代码:

var mod = require('express');

var auth = require('./acct_module.js');
var fs = require('fs');

var express = require('express');
var app = express();

app.use(express.bodyParser());

app.post('/login', function(request, response) {

console.log("POST called - try to login against the MongoDB.");

var credentials = request.body;
console.log("credentials = " + credentials);
console.log(credentials.username);
console.log(credentials.password);

auth.authenticate(credentials.username, credentials.password, function(result){
console.log("Authentication Result: " + result);
var code = result === 1 ? 200 : 401;
var message = result === 1 ? "Login succeeded!" : "Login failed!";
console.log("Response Code: " + code);
var res = {
message: message,
code : code
};

console.log(JSON.stringify(res));

response.statusCode = code;

response.json(res);

console.log("POST response sent.");
});

});

app.get('/login', function(request, response){
console.log("GET called - send back the HTML file.");
fs.readFile('login.html', function (err, data) {
if (err) {
response.writeHead(500, {'Content-Type': 'text/html'});
response.write("Request failed.");
response.end();
return;
}
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data);
response.end();

console.log("GET response sent.");
});
});

app.listen(10101);



登录页面login.html:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){
$( "#btn" ).click(function(){
// alert('Now calling the auth manager!');
var obj = {
username: $('#usrn').val(),
password: $('#pwd').val()
};
$.ajax({
type: "POST",
url: 'http://localhost:10101/login',
data: obj,
success: function (data, textStatus, jqXHR){
// alert('success called!');
var res = JSON.parse(jqXHR.responseText);
$('#status_message').html(res.message);
$('#status_code').html(res.code);
},
error : function(jqXHR, textStatus, errorThrown){
// alert('error called!');
var res = JSON.parse(jqXHR.responseText);
$('#status_message').html(res.message);
$('#status_code').html(res.code);
},
dataType: 'json'
});
})
});
</script>

</head>
<body>
<input type="text" id="usrn" name="usrn"/><br>
<input type="password" id="pwd" name="pwd"/><br>
<input type="button" id="btn" name="btn" value="LOGIN!"/><br><br>
<div id="status_message" name="status_message"></div><br>
<div id="status_code" name="status_code"></div><br>
</body>
</html>

关于javascript - Express POST - 返回的 JSON 被 JQuery 视为无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20364589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com