nodejs asynchronous.end()不处理邮政请求



我试图根据数据库查询返回文本 - 用于帐户注册 - 在 $。ajax Success上许多搜索,我无法理解下面的代码。

我找不到如何发送需要异步函数的HTTP响应,如果我尝试这样做,则根本无法处理或检测到该请求。

我认为问题在于我的res.end(" false")调用未及时调用,但代码对我来说是正确的。

我不想使用Express,所有回调都可以正常工作,但是我确定问题在 server.js 我放置注释

客户端:

$.ajax({
     async: true,
     dataType: "text",
     type: 'POST',
     url: 'http://192.168.0.23:3000',
     data: JSON.stringify(account_info),
     contentType: 'application/json; charset=utf-8',
     success: function (res) {
         console.log('Account registration : ' + res);
     },
     complete: function (res) {
            console.log('Account registration complete : ' +  
            JSON.stringify(res));
     },
    error: function (err) {
        console.log(err.responseText)
    }
});

服务器端:

server.js

const http = require('http');
var mongoose = require('mongoose');
var Visitor = require('./models/visitor.js');
var Account = require('./models/account.js');
var api = require('./controllers/api.js');
var isExisting = api.isExisting;
var saveData = api.saveData;
const port = 3000;
const server = http.createServer();
console.log('server is listening on ' + port);
server.listen(port);
server.on('request', function (request, response) {
    response.setHeader('Access-Control-Allow-Origin', '*');
    response.setHeader('Access-Control-Allow-Methods', 'POST');
    response.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    console.log(request.method);
    var body = '';
    request.on('data', function (data) {
        body += data;
    });
    request.on('end', function () {
        //In case there's content in the POST request
        if (body) {
            console.log('nRequest content:' + body + 'n');
            body = JSON.parse(body);
            mongoose.Promise = global.Promise;
            mongoose.connect('mongodb://localhost/someDB', {
                useMongoClient: true
            });
            //Pattern = ACCOUNT_REGISTRATION
            if (body.pattern == 'account_registration') {
                var value = {
                    email: body.email
                }
                var new_data = new Account(Account.store(body));
                //Check if account_name or website URL already in db
                // exist returning the callback
                isExisting(Account, value, function (exist) {
                    console.log(exist);
                    if (!exist) {
                        saveData(new_data);
                        //If you dont remove this line, the request is not detected by nodeJS
                        response.end('true');
                    } else {
                        console.log('nAccount already exist.');
                        //If you dont remove this line, the request is not detected by nodeJS
                        response.end('false');
                        mongoose.connection.close();
                        }
                    });
                }
            }
            //Here it's working good but If I remove this line it'll not handle the request at all
            response.end('oko');
        });
    });

api.js

// The API controller
var mongoose = require('mongoose');
//Send some new_data to db
exports.saveData = function (new_data) {
    //Data saving into MongoDB database
    new_data.save(function (err) {
        if (err) {
            throw err;
        }
        console.log('nData successfully added.');
        // We need to disconnect now
        mongoose.connection.close();
    });
}
exports.isExisting = function (ModelName, value, callback) {
    ModelName.count(value, function (err, count) {
        if (err)
            throw err;
        if (count == 0)
            callback(false);
        else
            callback(true);
    });
}

上次编辑:简而言之,

这是我不删除最后一行时得到的(正常行为,但是我无法获得异步响应

server is listening on 3000 
OPTIONS 
POST Request content:{"*****"}//real data already in db 
true //This is isExisting() callback
Account already exist. 

但是,当我删除最后一个响应时。End('oko'),选项之后的所有内容都不会出现...

我现在知道这个问题。

您正在提出CORS请求。所有CORS请求在发送实际请求之前先将选项请求发送到服务器,以检查访问控制标头是否实际允许服务器处理请求。

,由于您的请求处理程序检查是否存在fose.pattern(不存在选项请求),因此响应永远不会发送。

因此,该请求永远不会得到响应,而您的邮政请求永远不会到达服务器,因为它没有从选项请求中获得的权限。

因此,如果添加诸如 if ( method === 'OPTIONS' ) { response.end() } else if ( body ) { ... }之类的东西,您将确保可以处理选项。

确保确保所有请求都得到回答,即使您只是回答错误或404。

最新更新