【问题标题】:Get file path from request从请求中获取文件路径
【发布时间】:2014-04-10 21:56:09
【问题描述】:

我有以下文件: app.js

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen(8000);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
if (err) {
  res.writeHead(500);
  return res.end('Error loading index.html');
}

res.writeHead(200);
res.end(data);
  });
}

index.html(此处仅显示“头部”):

<html lang="en" ng-app="Client">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="format-detection" content="telephone=no"/>
<meta name="viewport"
      content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, target-densitydpi=device-dpi"/>

<link rel="stylesheet" type="text/css" href="css/app.css"/>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
<link rel="stylesheet" type="text/css" href="css/slider.css"/>
<title>Web Client: Robot control</title>
</head>

我首先执行我的 nodejs 服务器:node app.js 当我跑步时

http://localhost:8000/index.html

即使请求是针对不同的文件,例如:css/app.css,服务器 (app.js) 返回 index.html 文件。所以我的输出是非常错误的。

我可以知道如何解析 app.js 中的请求,获取 url 字段,然后从中提取所需的文件名吗?

谢谢。

已解决 通过执行以下操作 -

  var pathname = url.parse(req.url).pathname;
  console.log("Request for " + pathname + " received.");
  fs.readFile(__dirname + pathname,

您还需要以下行:

var url = require('url');

【问题讨论】:

    标签: javascript html css node.js socket.io


    【解决方案1】:
    req.url
    

    这个变量就是你需要的,如果你请求127.0.0.1:8000/index.html,req.url就是/index.html;如果你请求 127.0.0.1:8000/css/filename,req.url 是 /css/filename

    【讨论】:

    • 我尝试这样打印 req.print:function handler (req, res) { console.log(req.path); ...但它一直在打印“未定义”。
    • @Jayson 很抱歉我的粗心回答,你应该试试 req.url。
    猜你喜欢
    • 2013-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-16
    • 1970-01-01
    • 2012-01-21
    相关资源
    最近更新 更多