【问题标题】:node.js socket.io - track requested urlnode.js socket.io - 跟踪请求的 url
【发布时间】:2013-03-26 23:43:00
【问题描述】:

我正在测试是否提供请求的 URL,但是当我尝试时:

http://localhost:4000/foo

浏览器说:Cannot GET /foo

我的服务器代码:

var express = require('express');
var app = express();
var http = require('http');
var server = http .createServer(app);
var io = require('socket.io').listen(server);
var url = require('url');





server.listen(4000);

app.get('/', function (request, response) {
var pathname = url.parse(request.url).pathname;
 console.log("currentpathname: "+pathname);
});

我想为:

 http://localhost:4000/foo

【问题讨论】:

  • app.get('/', . . .更改为app.get('*', . . .

标签: node.js url express socket.io


【解决方案1】:

Express 只处理你告诉它处理的路径,所有其他路径它返回 404 并带有类似 Cannot GET /foo 的消息

app.get('/' 只处理'/' 来处理你需要使用app.get'*' 的所有路径

请注意规范

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1'); 

等价于

express().all('*', function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1'); 

为了了解事情是如何工作的,我建议只玩一下核心 http 模块。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多