0
我有一個作爲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"
這裏是提琴手的請求的例子:
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"}
我在做什麼錯?
謝謝你,那是:) – Neil