2

How do you get the get request string into a viable, like if someone goes to www.mypage.com/yo , how can I get node to return "yo" into a variable?

var http = require('http');

var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  var stringrequested = ??????
  response.end(stringrequested);

});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

// Put a friendly message on the terminal
console.log("Server running");
4

2 回答 2

2

request.url包含请求的 uri:

var stringrqeuested = request.url; // /yo

如果你只想要“yo”,你可以像这样删除前导斜杠:

var stringrqeuested = request.url.substr(1); // yo

request.url也包含查询字符串,例如/yo?a=b&c=d。如果你不想这样,你需要解析 url:

var stringrequested = require('url').parse(request.url).pathname; // /yo
var stringrequested = require('url').parse(request.url).pathname.substr(1); // yo

这是文档中的一个示例。

node> require('url').parse('/status?name=ryan', true)
{ href: '/status?name=ryan',
  search: '?name=ryan',
  query: { name: 'ryan' },
  pathname: '/status' }
于 2013-07-15T08:26:06.870 回答
0

截断 URL 的第一个字符 ( /):

request.url.substr(1)
于 2013-07-15T08:27:42.207 回答