2016-06-19 2 views
1

URL api 끝점 http : // someserver:someport/some_api_url?_var1=1에서 JSON이 Node.js/Express.js 앱에 반환됩니다. 이 정의되지 않은 JSON 입력은 항상 동일한 형식을 가지며 수신 코드 (아래 참조)를 사용하여 새 JSON 객체로 변환해야합니다. 새로운 JSON 객체는 HTML로 전달되는 것을 포함하여 다양한 방법으로 처리 될 수 있습니다.새 JSON 객체로 정의되지 않은 JSON 캐스팅


영업 질문 : 특정 변화가 있도록 아래의 코드로 할 필요가있는 무엇
: {"1":"descriptive string"}의 형태 1) JSON은 새롭게 정의 된 JSON 객체로 캐스팅됩니다

dataElement.dataKeydataElement.descriptionString의 두 가지 속성을 가진 dataElement이라고할까요? 수정 될

Index is: 1 
Description is: descriptive string 


예제 코드 :

2) 사용자의 웹 브라우저로 다시 전송하는 HTML 응답은 UI 형식 dataElement.dataKeydataElement.descriptionString 포함 된 시동기


, 코드가 수정 될 필요가있다 :

app.get('/', function (req, res) { 

    var url = 'http://someserver:someport/some_api_url?_var1=1' 

    http.get(url, function (resInner) { 
    var body = ''; 

    resInner.on('data', function (chunk) { 
     body += chunk; 
    }); 

    resInner.on('end', function() { 
     var fullResponse = JSON.parse(body); 

    // code to parse JSON into new JSON object, which is passed into HTML 
    var indexStr = key; 
    var descriptionStr = fullResponse[key]; 
    var dataElement = {"dataKey" : key, "descriptionString" : descriptionStr}; 
    var htmlResp = 'Index is: '+${dataElement.dataKey}+'<br> Description is: '+${dataElement.descriptionString}; 
    res.send(htmlResp); 

    }); 
}).on('error', function (e) { 
    console.log("Got an error: ", e); 
}); 

}); 


현재 웹 ER ROR : 순간
은, 위의 코드는 다음과 같은 오류주고있다 :

/home/user/nodejs_apps/express_helloworld/myapp/app.js:139 
     var htmlResp = 'Index is: '+${dataElement.dataKey}+'<br> Description is: '+${dataElement.descriptionString}; 
          ^
SyntaxError: Unexpected token { 
    at exports.runInThisContext (vm.js:53:16) 
    at Module._compile (module.js:387:25) 
    at Object.Module._extensions..js (module.js:422:10) 
    at Module.load (module.js:357:32) 
    at Function.Module._load (module.js:314:12) 
    at Function.Module.runMain (module.js:447:10) 
    at startup (node.js:142:18) 
    at node.js:939:3 
+0

'키'는 어디에서 왔습니까? – adeneo

+0

그러면 다른 곳에서 정의 된'key' 변수가 있고 API는 유효한 JSON을 반환합니다. 여기서 key 중 하나는 실제로'key' 변수를 – adeneo

+0

으로 설정 한 것과 같습니다. 따라서' 키'변수? – adeneo

답변

1

이 오류가 일부 무효 템플릿 언어를 사용하는 것 같다 당신의 문자열 연결에서 오는을하고 key 변수, 어떤 정의되지 않은, 당신은

이 예에서는이 방법 대신

app.get('/', function(req, res) { 

    var url = 'http://someserver:someport/some_api_url?_var1=1' 

    http.get(url, function(resInner) { 
     var body = ''; 

     resInner.on('data', function(chunk) { 
      body += chunk; 
     }); 

     resInner.on('end', function() { 
      var fullResponse = JSON.parse(body); 

      // code to parse JSON into new JSON object, which is passed into HTML 
      var keys  = Object.keys(fullResponse); 
      var firstKey = keys[0]; 
      var descriptionStr = fullResponse[firstKey]; 
      var dataElement = { 
       "dataKey": firstKey, 
       "descriptionString": descriptionStr 
      }; 
      var htmlResp = 'Index is: ' + dataElement.dataKey + '<br> Description is: ' + dataElement.descriptionString; 

      res.send(htmlResp); 
     }); 
    }).on('error', function(e) { 
     console.log("Got an error: ", e); 
    }); 

}); 
0

을 시도 실제로 Object.keys 등으로 열쇠를 얻을 수 있고, 당신이있어 TR ying을 사용하여 template strings을 사용했지만 잘못 사용하여 오류가 발생했습니다.

`Hello World, the expression "1+2" evaluates to ${1+2}` ==> `Hello World, the expression "1+2" evaluates to 3` 

템플릿 문자열은 SE 여기 인라인 코드를 삽입 할 때 사용하는 역 따옴표를 사용 :이 템플릿 문자열의 형식입니다. 그래서, 문제 라인은 다음과 같이 가정한다 :

그 구문 오류 이외의
var htmlResp = `Index is: ${dataElement.dataKey}`<br> Description is: `${dataElement.descriptionString}`; 

, 나는 당신의 코드로 문제를 볼 수 없었다,하지만 누가 알 겠어? ;)

희망은 도움이 될 수 있습니다!

관련 문제