首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NodeJS asynchronous.end()不处理POST请求

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

Stack Overflow用户
提问于 2017-12-29 17:11:50
回答 1查看 61关注 0票数 0

我试图在$.ajax success'参数上返回基于$.ajax success‘参数的基于数据库查询的文本--用于帐户注册,经过多次搜索,我无法了解下面的代码有什么问题。

我找不到如何发送需要异步函数的http响应,如果我尝试这样做,请求就根本不会被处理或检测到。

我认为问题在于我的那个res.end("false")调用没有被及时调用,但是在我看来代码是正确的。

我不想使用express,所有回调都在正常工作,但是我确信问题在server.js上,我在这里发表了评论

客户端:

代码语言:javascript
复制
$.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

代码语言:javascript
复制
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

代码语言:javascript
复制
// 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);
    });
}

最后一次编辑:

当我不移除最后一行时,这就是我得到的结果(正常行为,但是,我不能得到异步响应

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-29 17:49:09

我现在明白这个问题了。

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

由于您的请求处理程序检查是否存在一个body.pattern (对于选项请求不存在),所以不会发送响应。

因此,请求永远不会得到响应,您的POST请求也不会到达服务器,因为它没有从选项请求获得这样做的许可。

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48025991

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档