Node.js在首次启动时给出了无法预测的Ajax响应 [英] Node.js gives unpredictable ajax response on the first time of startup

查看:80
本文介绍了Node.js在首次启动时给出了无法预测的Ajax响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用node.js作为后端,使用canjs作为前端库.

I am using node.js as back end and canjs as front end library.

节点代码:

var express = require('express');
var app = express();
var http = require("http");
var fs = require("fs");
var cons = require('consolidate')

app.configure(function(){
      app.engine('html', cons.handlebars);
      app.set('view engine', 'html');
      app.set('views', __dirname)
      app.use(express.favicon())
      app.use(express.logger('dev'))
      app.use(express.static(__dirname ))
      app.use(express.bodyParser())
      app.use(express.methodOverride())
      app.use(express.cookieParser("secret"))
      app.use(express.session({ secret: 'keyboard cat' }))
      app.use(app.router)
    });

app.init = function(){
    fs.readFile('./sample.json', 'utf8', function(error, data) {
        if (error) {
            throw(error);
        }
        else
            app.set("json", data);
    })};

app.get('/things', function(req, res){
    app.init();
    res.set('Content-Type', 'text/json');
    res.send(app.get("json"));
});

app.get('/things/:id', function(req, res){
    app.init();
    res.set('Content-Type', 'text/json');
    res.send((JSON.parse(app.get("json")))[req.param('id')]);
});

app.get('/main.html', function(req, res){
    app.init(function(error, data){
        if (error) {throw error}
        res.render('main.html');
    });
});

app.listen(3000);

Can.js代码:

Todo = can.Model({
    findAll: "GET /things",
    findOne: "GET /things/{id}",
},{});

$(document).ready(function(){

    Todo.findAll({}, function(todos){
        console.log(JSON.stringify(todos));
    })

    Todo.findOne( { id: 1 }, function( todo ) {
        console.log( todo );
    })

});

HTML:

<script type="text/javascript" charset="utf-8" src="./jquery-1.8.2.js"></script>
<script type="text/javascript" charset="utf-8" src="./can.jquery-1.0.7.js"></script>
<script type="text/javascript" charset="utf-8" src="./can.fixture.js"></script>
<script type="text/javascript" charset="utf-8" src="./master.js"></script>

JSON:

{"0":{"id":1,"name":"do the dishes"},"1":{"id":2,"name":"go to dentist"},"2":{"id":3,"name":"go swimming"},"4":{"id":5,"name":"masturbate"}}

每次启动服务器时,控制台都会找到两个函数(findAll和findOne)的ajax GET响应,返回未定义或500错误:

Each time the server is started up, the console will find the ajax GET response for both functions (findAll and findOne) returning either undefined or 500 error:

XHR finished loading: "http://localhost:3000/things". jquery-1.8.2.js:8416
undefined master.js:12

GET http://localhost:3000/things/1 500 (Internal Server Error) jquery-1.8.2.js:8416
XHR finished loading: "http://localhost:3000/things/1". jquery-1.8.2.js:8416
Uncaught TypeError: Function.prototype.apply: Arguments list has wrong type 

但是,如果我在此之后刷新页面,则这两个功能将正常工作,给出:

But if I refresh the page after this, the two functions will work normally, giving:

XHR finished loading: "http://localhost:3000/things". jquery-1.8.2.js:8416
{"0":{"id":1,"name":"do the dishes"},"1":{"id":2,"name":"go to dentist"},"2":{"id":3,"name":"go swimming"},"4":{"id":5,"name":"masturbate"},"length":0,"_namespace":".observe2"} master.js:12
XHR finished loading: "http://localhost:3000/things/1". jquery-1.8.2.js:8416
Constructor {name: "go to dentist", _data: Object, id: 2, _namespace: ".observe3"}
 master.js:16

怎么回事?

推荐答案

问题是您在app.init中的fs.readfile回调设置了它的值之前正在调用app.get("json");(这发生在第一次调用app.init();返回).

The problem is that you're calling app.get("json"); before its value has been set by the fs.readfile callback in app.init (which occurs sometime after the first call to app.init(); returns).

您可能应该将代码更改为仅调用app.init一次,并且在其工作完成之前不要监听请求.

You should probably change your code to only call app.init once, and don't listen for requests until its work completes.

app.init = function(callback){
    fs.readFile('./sample.json', 'utf8', function(error, data) {
        if (error) {
            throw(error);
        } else {
            app.set("json", data);
            callback();
        }
    });
};

...

app.init(function() {
    app.listen(3000);
});

这篇关于Node.js在首次启动时给出了无法预测的Ajax响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆