如何使用Express获取URL参数?

时间:2018-04-21 09:30:45

标签: node.js express url query-string

我想得到一篇文章PageId'来自URL的数字如下,但终端窗口没有显示URL查询参数...

我编码的问题是什么?

谁能告诉我怎么能这样做?

非常感谢。

我尝试了以下内容:

https://localhost:8090/articlePage.html?articlePageId='+item.ID

console.log(fullUrl)      // http://localhost:8090/
console.log(req.path)     // /
console.log(req.params)   // {}
console.log(req.query.articlePageId)  // undefined

这是服务器

const express = require('express');
const expressStatic = require('express-static')
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session');
const multer = require('multer');
const multerObj = multer({dest:'./static/upload'});
const consolidate = require('consolidate');

const server = express();

server.use(bodyParser.urlencoded({extended:true}));
server.use(multerObj.any());

server.use(cookieParser());
(function(){
const keys = [];
for(var i=0;i<1100000;i++){
 keys[i] = 's_' + Math.random();
}
server.use(cookieSession({
  keys,
  name:'sess_id',
  maxAge:20*60*1000
 }));
})()

server.engine('html',consolidate.ejs);
server.set('views','template');
server.set('view engine','html');

server.use('/',require('./router/web/index')());

server.use('/admin',require('./router/admin/index')());

server.use(expressStatic('./static/'))
server.listen(8090)

这是index.js

router.use('/', require('./articlePage')())

这是articlePage.js

var express = require('express');
var mysql = require('mysql');
var urlLib = require('url');
var querystring = require('querystring')

var db = mysql.createPool({
  localhost: 'localhost',
  user: 'root',
  password: '123456',
  database: 'blog'
})

module.exports = () => {
var router = express.Router();
router.get('/', (req, res) => {
var fullUrl = req.protocol + '://' + req.get('host') +req.originalUrl;
console.log(fullUrl)
console.log(req.path)
console.log(req.params)
console.log(req.query.articlePageId)
db.query(`SELECT * FROM articles_table WHERE ID='articlePageId'`, (err, page) => 
{
  if (err) {
  console.error(err);
  res.status(500).send('database error').end();
} else {
  res.send(page);
}
})
})
 return router
}

0 个答案:

没有答案