我正在學習nodejs,並且遇到了一些問題。 我正在創建一個提供html文件的服務器。該HTML文件有一個js,它執行xmlHttpRequest來獲取數據。我要檢索的數據要發送回我的服務器進行處理。最後一步是我卡住的地方。每次服務器停止時,我都希望收到服務器中的URL來處理它們。將數據發送到nodejs服務器
Server.js
var http = require('http'),
url = require('url'),
path = require('path'),
fs = require('fs');
var mimeTypes = {
"html": "text/html",
"js": "text/javascript",
"css": "text/css"};
http.createServer(function(request, response){
var uri = url.parse(request.url).pathname;
var filename = path.join(process.cwd(), uri);
fs.exists(filename, function(exists){
if(!exists){
console.log(filename + " does not exist");
response.writeHead(200, {'Content-Type' : 'text/plain'});
response.write('404 Not found\n');
response.end();
return;
}
var mimeType = mimeTypes[path.extname().split(".")[1]];
response.writeHead(200, {'Content-Type' : mimeType});
var fileStream = fs.createReadStream(filename);
fileStream.pipe(response);
});
response.on('end', function(){
console.log("Request: " + request);
console.log("Response: " + response);
});
}).listen(1337);
Client.js
function getURLs(){
var moduleURL = document.getElementById("url").value;
var urls = [];
console.log(moduleURL);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
var xml = xmlhttp.responseXML;
var items = xml.children[0].children[0].children;
for(var i = 13; i<items.length; i++){
urls.push(items[i].children[1].getAttribute("url")+"&hd=yes");
}
//console.log(urls);
sendDataToServer(urls);
}
}
xmlhttp.open("GET", moduleURL, true);
xmlhttp.send();
}
function sendDataToServer(urls){
//console.log(urls);
var http = new XMLHttpRequest();
http.open("POST", "http://127.0.0.1:1337/", true);
http.send(urls);
}
我在瀏覽器
POST http://127.0.0.1:1337/ net::ERR_CONNECTION_REFUSED
的控制檯讓這個和這個在cmd中節點
events.js:72 throw er; // Unhandled 'error' event ^Error: EISDIR, read
雖然它正在處理數據,但我想將進度發送回客戶端以顯示在最終用戶的html頁面上。我已經有了進展的功能,它只是發送/接收我卡住的數據。請有人指出我正確的方向嗎?
我也知道,有快遞和其他模塊,我可以使用,但學習節點我試圖這樣做。所以我希望有人能把我推向正確的方向。
它看起來不像你的服務器有一條路線,可以捕獲ajax URL,不管是什麼? – adeneo 2015-03-18 22:02:44
你能多解釋一下嗎? – mXX 2015-03-18 22:09:42
當您將POST數據發送到URL時,服務器必須捕獲它。你將它發送給'/',並且你有一個捕獲所有東西的服務器,但它似乎沒有做任何事情或返回任何東西,也許更像這樣 - > ** http://jsfiddle.net/5eeLn17o/** – adeneo 2015-03-18 22:15:21