获取请求不在服务器端工作

时间:2015-07-12 23:38:06

标签: javascript ajax node.js express

我使用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);

2 个答案:

答案 0 :(得分: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'));

答案 1 :(得分: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);
相关问题