[英]NodeJS asynchronous.end() not working on POST request
我試圖返回基於數據庫查詢的文本-用於帳戶注冊-在$ .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.
但是當我刪除最后一個response.end('oko')時,OPTIONS之后的所有內容都不會出現...
我現在了解這個問題。
您正在提出CORS要求。 並且所有CORS請求都先向服務器發送OPTIONS請求,然后再發送實際請求,以檢查訪問控制標頭是否實際上允許服務器處理該請求。
由於您的請求處理程序會檢查body.pattern的存在(對於OPTIONS請求而言將不存在),因此永遠不會發送響應。
因此,該請求永遠不會得到響應,並且您的POST請求也永遠不會到達服務器,因為它沒有獲得OPTIONS請求的許可。
因此,如果您添加類似if ( method === 'OPTIONS' ) { response.end() } else if ( body ) { ... }
您將確保可以處理這些選項。
為了安全起見,即使您只是回答有錯誤或404,也請確保所有請求都得到答復。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.