如何在url中返回请求的字符串?

时间:2013-07-15 08:23:14

标签: node.js

如何将获取请求字符串变为可行,如果有人访问www.mypage.com/yo,我怎样才能让节点将“yo”返回到变量中?

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");

2 个答案:

答案 0 :(得分:2)

request.url包含请求的uri:

var stringrqeuested = request.url; // /yo

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

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

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

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

以下是documentation

中的示例
node> require('url').parse('/status?name=ryan', true)
{ href: '/status?name=ryan',
  search: '?name=ryan',
  query: { name: 'ryan' },
  pathname: '/status' }

答案 1 :(得分:0)

切断网址的第一个字符(/):

request.url.substr(1)