2015-07-12 172 views
0

我正在使用nodejs和express模塊​​製作基本的web服務器。它必須能夠響應POSTGET請求。 POST工作正常,但GET不返回任何內容。在控制檯中有一個錯誤parserrorSyntaxError: Unexpected end of input at Object.parse (native) at jQuery.parseJSON錯誤的textStatus。我是NodeJS和Express的新手,請告訴我哪裏出錯了。獲取請求無效服務器端

var express = require('express'), 
    server = express(), 
    fs = require('fs'); 

server.use(express.static('../client')); 

server.post('/students.json', function (req, res) { 
    var bodyStr = ''; 
    req.on('data', function (chunk) { 
     bodyStr += chunk.toString(); 
    }); 
    req.on('end', function() { 
     fs.readFile('students.json', function (err, data) { 
      var encodedObj = data.toString('utf8'), //encoding what's inside of .json into human symbols 
       parsedObj = JSON.parse(encodedObj); 
      parsedObj.push(JSON.parse(bodyStr)); //adding newly created parsed obj into array 

      fs.writeFile('students.json', JSON.stringify(parsedObj), function (err) { //rewriting file with new array 
       if (err) { 
        console.log(err); 
       } 
      }); 
     }); 
    }); 
}); 

server.get('/students.json', function (req, res) {//what's wrong??? 
    res.send(); 
}); 

var server = server.listen(8888); 
+0

這裏運行它沒有產生任何錯誤。在我的計算機上調用get /'student.json'時,它沒有正確返回任何內容。我會認爲它必須在別處的代碼中? –

+0

這就是問題所在,我想將students.json文件返回給客戶端。我怎樣才能做到這一點? – Ivan

回答

1

你在試圖res.send()?它看起來對我來說是空的。嘗試:

res.send('Hello World!'); // A string 

......或者......

res.send([{'name': 'Joe Student'},{'name': 'Sally Goestoskuhl'}]); // Array 

......或者......

res.send({}); // Empty json response 

......或者......

res.send(404); // Any integer is considered an HTTP error code 

...或...

res.setHeader('Content-Type', 'application/json'); 
res.send(JSON.stringify({ variable: 'value' })); 

......或者......

// Assuming your json is in the public folder... 
res.sendFile(path.join(__dirname, '../public', 'students.json')); 
+0

我想發送我的students.json文件。怎麼做? – Ivan

0

res.send();它自己只是發送一個空的響應。 如果你然後嘗試json_decode它,你會得到一個錯誤。

如果我正確解釋您的問題,您希望POST和GET都返回相同的結果嗎?

你能做到這一點倒也乾脆像這樣:

function sendJSON(req, res) 
{ 
    //JSON code from your existing server.post 
} 

app.get('/students.json', sendJSON); 
app.post('/students.json', sendJSON); 
+0

其實我想返回json文件。我使用Backbone從客戶端獲取它。這聽起來很簡單,但我真的找不到答案如何做到這一點。 – Ivan