我们可以在Node.js中获取查询字符串中的变量吗,就像在PHP中获取$_get中的变量一样?

我知道在Node.js中,我们可以获取请求中的URL。是否有获取查询字符串参数的方法?


当前回答

如果您想避免表达,请使用以下示例:

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

function func111(req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  var q = url.parse(req.url, true);
  res.end("9999999>>> " + q.query['user_name']); 
}

http.createServer(func111).listen(3000); 

用法:

curl http://localhost:3000?user_name=user1

通过yl

其他回答

我从其他答案中吸取了教训,并决定在整个网站中使用此代码:

var query = require('url').parse(req.url,true).query;

那你可以打电话

var id = query.id;
var option = query.option;

get的URL应该在哪里

/path/filename?id=123&option=456

像我一样

npm  query-string
import queryString from "query-string";

export interface QueryUrl {
  limit?: number;
  range?: string;
  page?: number;
  filed?: string;
  embody?: string;
  q?: string | object;
  order?: number;
  sort?: string;

}

 let parseUri: QueryUrl = queryString.parse(uri.query);

对于Express.js,您需要执行req.params:

app.get('/user/:id', function(req, res) {
  res.send('user' + req.params.id);    
});

如果您想避免表达,请使用以下示例:

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

function func111(req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  var q = url.parse(req.url, true);
  res.end("9999999>>> " + q.query['user_name']); 
}

http.createServer(func111).listen(3000); 

用法:

curl http://localhost:3000?user_name=user1

通过yl

因此,有两种方式可以接收此“id”:1) 使用params:代码params看起来像:假设我们有一个阵列,

const courses = [{
    id: 1,
    name: 'Mathematics'
},
{
    id: 2,
    name: 'History'
}
];

然后,对于params,我们可以执行以下操作:

app.get('/api/posts/:id',(req,res)=>{
    const course = courses.find(o=>o.id == (req.params.id))
    res.send(course);
});

2) 另一种方法是使用查询参数。因此url看起来像“…..\api\xyz?id=1”,其中“?id=1“是查询部分。在这种情况下,我们可以执行以下操作:

app.get('/api/posts',(req,res)=>{
    const course = courses.find(o=>o.id == (req.query.id))
    res.send(course);
});