为什么这不将"Success"返回给客户端?



我想做的只是在找到他们要查找的查询后向客户端发送一条消息。当写磁头在功能之外时,它工作正常。但当它在回调中时,它只返回一个空格(什么都不返回(。为什么会这样?回调中的其他一切都有效,为什么我不能发送一个简单的成功消息??

主页.html

这是一个简单的密码和用户名框,我张贴到后端。我正在使用xhr。

<!DOCTYPE html>
<html>
<head>
<title>
Little structure
</title>
<link rel="shortcut icon" href="img/favicon.ico">
</head>
<body>
<div id="demo">
<a href = "home.html">HOME</a>
<h1 id = "factor">Click ere</h1>
<button type="button" onclick="loadDoc()">Submit</button></br>
<input id = "userName"></input> </br>
<input id = "userPW" type = "password"></input></br>
</div>
<script>
// First you must post and check to see if account exists
function loadDoc() {
//initiate POST request
var xhr = new XMLHttpRequest();
xhr.open("POST", 'http://localhost:3000', false);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
// Request finished. Do processing here
document.getElementById("factor").innerHTML = this.responseText;
console.log(this.responseText);
}
}
xhr.send("userName=" + userName + "&userPW=" + userPW); 

}
</script>
</body>
</html>

Server.js

我写的问题代码在第52行。

var http = require('http');
var fs = require('fs');
var qs = require('querystring');
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert').strict;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
// Create a new MongoClient
const client = new MongoClient(url);
var server = http.createServer(function (req, res) {
client.connect(function(err) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
// Get the documents collection
const collection = db.collection('doc');
if(req.method == "GET")
{
if(req.url === '/')
{
fs.readFile('home.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);                            
res.end();
});
}
}
else if (req.method == 'POST') {
console.log("inside POST: ", req.method);
var body = '';
req.on('data', function (data){
body += data;
})
req.on('end', () => {
var postData = qs.parse(body);
//Verify the login post request. If ur data exists
if(req.url == "/")
{ 
var fn = function(err, result){
console.log(result);
console.log(err);
res.writeHead(200);
res.end("SUCCESS");
}
collection.findOne(postData, fn);
}
res.end();
})
}
});
});
server.listen(3000);
console.log("listening on 3000");

这是一个异步问题。在62号线上,您可以拨打res.end()。第52行中定义的函数被用作第60行中的异步回调。

在第62行调用res.end()之后,回调最终被调用。很可能您只想将该行封装在else中,如下所示:

if(req.url == "/")
{ 
var fn = function(err, result){
console.log(result);
console.log(err);
res.writeHead(200);
res.end("SUCCESS");
}
collection.findOne(postData, fn);
}
else{
res.end();
}

这样,res.end()将只被调用一次,无论是在if内部的回调中还是在else内部。

最新更新