javascript - 如何使用 Node JS Http/Https 模块获取 URL 参数

标签 javascript node.js http parameters url-routing

我正在编写 Web 应用程序的后端程序。我正在做 api,我需要能够在 URL 中发送数据。例如:

www.example.com/posts/123456789

现在我只有:

www.example.com/posts/?q=123456789

我想知道我是否可以做一些类似于 express 模块用冒号声明参数的事情。但是我想用 node http 模块来完成它,因为我已经用它编写了所有路由,移动到 express 并且必须记住它的功能将是一个巨大的痛苦。

如果这不可能,请告诉我,我将不得不坚持使用查询字符串。

最佳答案

如果我正确理解你的问题,你会做这样的事情。

我会给你完整的服务器代码,传递并运行它。你自己看看

例如,这段代码所做的是 -> localhost:8080/month?9 当你将它传递到浏览器时,控制台将打印出 9

const http = require('http');
const url = require('url');

http.createServer(function (req, res) {
  const queryObject = url.parse(req.url,true).query; <---- Here is where you "catch" the URI parameters
  console.log(queryObject); <-- here you display them

  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end('Feel free to add query parameters to the end of the url');
}).listen(8080);

关于javascript - 如何使用 Node JS Http/Https 模块获取 URL 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69889320/

相关文章:

javascript - 为什么 `lodash.map([' A'], String.prototype.toLowerCase.call)` 不起作用?

javascript - 无法使用 Angular 的 HttpClient 上传图片

javascript - Javascript中的 "|| {}"是什么意思?

javascript - 如何在 Javascript 中复制 Python 的 dict.items()?

javascript - async array.map() 和 async npm 包之间的区别

Http header -缓存控制 : max-age - behaviour?

http - get 请求中的参数可以有多长?

javascript - 为什么这个简单的 jQuery 片段不起作用?

javascript - 在 UIWebView 上加载 javascript

javascript - Require 在 NodeJS 应用程序中无法识别