在向Node应用程序发出请求后调用错误回调方法

时间:2015-11-10 12:48:59

标签: node.js httprequest

我有一个作为Web服务器运行的节点应用程序,接受包含文件名,文件路径和文件内容的POST请求。它生成文件并返回201消息。

以下是代码:

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

var writeFile = function(pathname, fileName, content)
{
    fs.writeFile(pathname + fileName, content, function(err) 
    {
        if(err) 
        {
            return console.log(err);
        }
        console.log("The file was saved!");
        return "";
    });
}


var handleRequest = function(request, response)
{
    try
    {
        if(request.url == "/save")
        {
            var fullBody = "";
            request.on('data', function(chunk) 
            {
                fullBody += chunk.toString();
            });


            request.on('end', function() 
            {
                value = JSON.parse(fullBody);
                var result = writeFile(value.savePath, value.fileName, value.fileText);
                response.writeHead(201, {'Access-Control-Allow-Origin': '*'});
                response.end();
            });
        }
        else
        {
            response.writeHead(200, {'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': '*'});
            response.write('File Service Running');
            response.end();
        }
    }
    catch(error)
    {
        response.writeHead(500, {'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': '*'});
        response.end(error);
    }
}

http.createServer(handleRequest).listen(3000);

然后我有一个网页就像这样调用这个服务:

var data = JSON.stringify({ savePath: path, fileName: fileName, fileText: xml });

    $.ajax({
        url: "http://localhost:" + port + "/save",
        type: "POST",
        crossDomain: true,
        data: data,
        dataType: "json",
        success: function (response)
        {
            handler();
        },
        error: function (xhr, status, error)
        {
            alert(status);
        }
    });

我通过节点服务进行调试,它可以毫无问题地完成所有操作。但是,将调用错误回调而不是成功回调

错误参数是:

xhr: { readyState:4, responseText: "File Created", status: 201, statusText: "Created" }

status: "parsererror"

error: "Unexpected end of input"

以下是来自fiddler的请求示例:

POST http://localhost:3000/save HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Content-Length: 64
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://localhost:44301
X-FirePHP-Version: 0.0.6
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
DNT: 1
Referer: http://localhost:44301/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8

{"savePath":"C:\\test","fileName":"14735.xml","fileText":"test"}

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我已经尝试过您的示例,我通过删除

来实现它
dataType: "json"

可以在jQuery docs中找到此行为的原因,因为dataType代表

  

您期望从服务器返回的数据类型。

您可以通过保留但是添加

来仔细检查
response.send('{ "test": 1 }');

在写入标题后发送response.end()之前。