Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 同时使用res.send和res.json_Javascript_Json_Node.js_Express - Fatal编程技术网

Javascript 同时使用res.send和res.json

Javascript 同时使用res.send和res.json,javascript,json,node.js,express,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":

我想创建一个包含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()
还将转换无效json的非对象,例如null和undefined

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

text/plain
对于jsonp?@Bergi我认为text/plain,因为config.js将由客户端的jQuery访问。如何访问?解析为JSON,执行为JSONP,或读取并显示为文本?@Bergi解析为JSONThen为什么要将
var JSON=
放在那里?只需使用
res.json(json)
就可以了,别无选择!我不完全明白你的意思,但如果有帮助,你可以使用res.json()而不是res.send()