一起使用res.send和res.json

时间:2014-02-24 04:24:10

标签: javascript json node.js express

我想创建一个包含JSON代码的文件config.js。 这是我在app.js上的代码

app.get('/config.js', function(req, res) {
  var JSON = {
    "info": {
        "level1":  "Jeopardy Ready",
        "level2":  "Jeopardy Contender",
        "level3":  "Jeopardy Amateur",
        "level4":  "Jeopardy Newb",
        "level5":  "Stay in school, kid..." // no comma here
    }
  };
  res.format({'text/plain': function(){
    res.send(" var JSON = ");
  }
  });
 res.json(JSON);

});

我想在config.js

中得到结果
var JSON = {
    "info": {
        "level1":  "Jeopardy Ready",
        "level2":  "Jeopardy Contender",
        "level3":  "Jeopardy Amateur",
        "level4":  "Jeopardy Newb",
        "level5":  "Stay in school, kid..." // no comma here
    }
    ]
  };

知道怎么做吗? 在我的代码中,我试图一起使用res.send和res.json,但它无法工作。

3 个答案:

答案 0 :(得分:0)

试试这个:

app.get('/config.js', function(req, res){
 var JSON_ = {
   "info": {
       "level1":  "Jeopardy Ready",
       "level2":  "Jeopardy Contender",
       "level3":  "Jeopardy Amateur",
       "level4":  "Jeopardy Newb",
       "level5":  "Stay in school, kid..." // no comma here
   }
 } 
 var JSONstr= JSON.stringify(JSON_);
 res.send("var JSON = " + JSONstr + ";");
});

您的代码示例中也存在拼写错误(第10行的方括号)

答案 1 :(得分:0)

传递对象或数组时,方法是相同的,但res.json()也会转换非对象,例如null和undefined,这些对象是无效的JSON。

使用res.send

var object = {
};
res.send(JSON.stringify(object));

该方法最终以res.send()结束:

 this.charset = this.charset || 'utf-8';
 this.get('Content-Type') || this.set('Content-Type', 'application/json');
 return this.send(body);

使用res.json

res.json(object)

答案 2 :(得分:0)

简单

res.send(JSON.stringify(JSON_));

在客户端

success: function(response){
  try{ 
    response = JSON.parse(response);
    // other logic 
  }
  catch(e){
     // your own logic, when json is not valid!
  }
}