节点:从URL获取JS文件的var

时间:2016-03-04 21:20:45

标签: javascript node.js

我有一个请求调用,它将调用包含var:

的javascript文件
var url = 'http://' + _environment + '/services.js';

request(url, function (error, response, body) {
   if (!error && response.statusCode === 200) {
       _services = body;
   }

   console.log(_services);
});

这将记录如下内容:

var services = {
     "production": {
          "global": {
               "id": "id",
               "test2": "http://test.com",
               "test": "/test/test.test",
               "test1": "test"
          }
     }
}

确切地说,这一行与我最终的结果相同:

var _services = var services = {
     "production": {
          "global": {
               "id": "id",
               "test2": "http://test.com",
               "test": "/test/test.test",
               "test1": "test"
          }
     }
}

如何将位于某个网址的js文件中的var传递给我的代码?

1 个答案:

答案 0 :(得分:0)

您可以使用exec(_services),但更好的办法是删除var部分并返回常规JSON,然后解析JSON。

让它归还..

{
     "production": {
          "global": {
               "id": "id",
               "test2": "http://test.com",
               "test": "/test/test.test",
               "test1": "test"
          }
     }
}

然后做var services = JSON.parse(_services);

<小时/> 或者,您可以创建一个脚本标记并将其追加..

// This is with jQuery, you can convert to standard JS
$("body").append("<script>"+_services+"</script>");
相关问题