2013-09-21 62 views
37

我有一個名爲「localhost:3000/returnStat」的服務,它應該將文件路徑作爲參數。例如'/BackupFolder/toto/tata/titi/myfile.txt'。Node.js:從請求中獲取路徑

如何在我的瀏覽器上測試此服務? 如何使用Express格式化此請求?

exports.returnStat = function(req, res) { 

var fs = require('fs'); 
var neededstats = []; 
var p = __dirname + '/' + req.params.filepath; 

fs.stat(p, function(err, stats) { 
    if (err) { 
     throw err; 
    } 
    neededstats.push(stats.mtime); 
    neededstats.push(stats.size); 
    res.send(neededstats); 
}); 
}; 
+0

沒錯創建一個REST調用看到這篇文章的http://erichonorez.wordpress。 com/2013/02/10/how-create-a-rest-api-with-node-js-and-express/ – lastboy

+0

和瀏覽器,僅用於快速測試 –

回答

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

var neededstats = []; 

http.createServer(function(req, res) { 
    if (req.url == '/index.html' || req.url == '/') { 
     fs.readFile('./index.html', function(err, data) { 
      res.end(data); 
     }); 
    } else { 
     var p = __dirname + '/' + req.params.filepath; 
     fs.stat(p, function(err, stats) { 
      if (err) { 
       throw err; 
      } 
      neededstats.push(stats.mtime); 
      neededstats.push(stats.size); 
      res.send(neededstats); 
     }); 
    } 
}).listen(8080, '0.0.0.0'); 
console.log('Server running.'); 

我沒有測試你的代碼,但其他的東西工作

如果你想從請求URL

var url_parts = url.parse(req.url); 
console.log(url_parts); 
console.log(url_parts.pathname); 

路徑信息1.如果你正在在我的示例中,URL參數仍然無法讀取文件,只是糾正了您的文件路徑。如果放在同一個目錄服務器代碼,它會工作的index.html ...

2.如果您有您要使用節點,那麼我會建議你使用像expressjs

一些框架來承載大文件夾結構

如果你想生解決方案的文件路徑

var http = require("http"); 
var url = require("url"); 

function start() { 
function onRequest(request, response) { 
    var pathname = url.parse(request.url).pathname; 
    console.log("Request for " + pathname + " received."); 
    response.writeHead(200, {"Content-Type": "text/plain"}); 
    response.write("Hello World"); 
    response.end(); 
} 

http.createServer(onRequest).listen(8888); 
console.log("Server has started."); 
} 

exports.start = start; 

來源:http://www.nodebeginner.org/

+0

我的代碼有效,但是如何才能檢索文件路徑(請求參數,例如'/BackupFolder/toto/tata/titi/myfile.txt') –

6

只需撥打req.url。應該做這項工作。你會得到像/something?bla=foo

+0

您示例中的路徑是'/ something'。 –

+5

使用'req.url.match('^ [^?] *')[0]'來顯示路徑 – epegzz

2

你可以在app.js文件中使用此。

var apiurl = express.Router(); 
apiurl.use(function(req, res, next) { 
    var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl; 
    next(); 
}); 
app.use('/', apiurl); 
1

基於正則表達式的@epegzz建議。

(url) => { 
    return url.match('^[^?]*')[0].split('/').slice(1) 
} 

返回一個包含路徑的數組。

2
req.protocol + '://' + req.get('host') + req.originalUrl 

req.protocol + '://' + req.headers.host + req.originalUrl //我喜歡這個,因爲它從代理服務器生存,獲得原始主機名