2016-02-27 116 views
0

在一個json文件上使用$ http.get(),但是響應是我正在使用的頁面的HTML代碼。也就是說,console.log(response)打印整個test.html文件。

main.js在nodejs上運行,它載入test.html。 test.html然後應該加載test.json。 console.log('here')打印並設置$ scope.hello並正確顯示。

main.js

var http = require("http"); 
var fs = require('fs'); 

http.createServer(function (request, response) { 
    var data = fs.readFile('test.html', function(err,data) { 
     response.writeHead(200, {'Content-Type': 'text/html'}); 
     response.write(data); 
     response.end(); 
    }); 
}).listen(8081); 

的test.html

<!DOCTYPE html> 
<html ng-app="App"> 
    <head> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"> 
    </script> 

    <script> 
    angular.module('App', []).controller('Ctrl', 
     function($scope, $http) { 
      console.log('here'); 
      $http.get('test.json').success(function(response) { 
       console.log(response); 
       $scope.hello = "hi guys"; 
      }); 
     } 
    ); 
    </script> 
    </head> 

    <body> 
    <div ng-controller="Ctrl"> 
    <p>{{hello}}</p> 
    </div> 
    </body> 
</html> 

test.json

{ "papers" :[ 
    { 
     "authors":"Zubrin, Robert M.; Baker, David A.; Gwynne, Owen", 
     "title":"Mars Direct: A Simple, Robust, And Cost Effective Architecture For The Space Exploration Initiative", 
     "titleLink":"http://www.marspapers.org/papers/Zubrin_1991.pdf", 
     "abstractName":"Abstract", 
     "abstractLink":"http://www.marspapers.org/abstr/Zubrin_1991abstr.htm",  
     "year":"1991", 
     "category":"MissionEngring", 
     "publcation":"" 
    } 
]} 
+0

它發佈了什麼html ..可能是一些錯誤編碼,它認爲更新您的文章,以獲得一些快速幫助.. – Prasad

+0

一個更多的事情在你的服務器端編碼你需要發送response.writeHead(200, { '內容 - 類型': '應用/ JSON'});而不是text/html – Prasad

+0

而不是發送test.html你需要查詢你的數據庫,然後在json中返回響應然後它的作品! – Prasad

回答

0

你的服務器是專門編程返回的test.html不管內容是什麼要求。您需要實際檢查request並提供相應的文件。

+0

我不關注。是的,節點將返回test.html的內容,但我會認爲當我加載頁面角部分將運行並加載json文件。 – joshbaldwin42

+1

@ joshbaldwin42 Angular只能加載你服務的數據,不管你從節點請求什麼,你都有特定的節點來返回'test.html'的內容。你可以去'http:// localhost:8081/iiwugeiugifugiugwygfiugriqgriuqgr',你會得到'test.html'的內容。你可以去'http:// localhost:8081/test.json',你會得到'test.html'的內容。不管你要求什麼URL,你都有特定的節點來**忽略請求**並提供'test.html'的內容。 – meagar

+0

我想我明白了。我假設$ http.get()是在角度上完成的,但我需要在$ http.createServer()函數中添加此功能來處理此請求。聽起來像我需要更多地查看節點。謝謝! – joshbaldwin42