NodeJS asynchronous.end()不能处理POST请求

时间:2017-12-29 17:11:51

标签: javascript jquery node.js http request

我尝试在 $。ajax success' 参数上返回基于数据库查询的文本 - 用于帐户注册 - 经过多次搜索,我可以&# 39;得到以下代码的错误。

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

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

我不想使用快递和所有回调都正常工作但是我确定问题出在 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. 

但是当我删除最后一个响应时(' oko'),OPTIONS之后的所有内容都没有出现......

1 个答案:

答案 0 :(得分:0)

我现在明白这个问题。

您正在提出CORS请求。并且所有CORS请求在发送实际请求之前首先向服务器发送OPTIONS请求,以检查访问控制头是否实际允许服务器处理请求。

由于您的请求处理程序检查了对于OPTIONS请求不存在的body.pattern的存在,因此永远不会发送响应。

因此,请求永远不会得到响应,并且您的POST请求永远不会到达服务器,因为它没有从OPTIONS请求获得许可。

因此,如果您添加if ( method === 'OPTIONS' ) { response.end() } else if ( body ) { ... }之类的内容,则可以确保选项得到处理。

为了安全起见,请确保所有请求都得到解答,即使您只是回答错误或404。