繁体   English   中英

一起使用res.send和res.json

[英]Use res.send and res.json together

我想创建一个包含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一起使用,但无法正常工作。

尝试这个:

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行的方括号)

传递对象或数组时,方法是相同的,但是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)

很简单

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!
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM