2017-04-22 86 views
1

我想在Node.js中使用Express訪問查詢參數。出於某種原因,req.params不斷出現作爲一個空的對象。這是我在server.js代碼:快速查詢參數

const express = require('express'); 
const exphbs  = require('express-handlebars'); 
const bodyParser = require('body-parser'); 
const https  = require('https'); 

//custom packages .. 
//const config = require('./config'); 
const routes = require('./routes/routes'); 


const port = process.env.port || 3000; 


var app = express(); 

//templating engine Handlebars 
app.engine('handlebars', exphbs({defaultLayout: 'main'})); 
app.set('view engine', 'handlebars'); 





//connect public route 
app.use(express.static(__dirname + '/public/')); 


app.use(bodyParser.json()); 

//connect routes 
app.use('/', routes); 






app.listen(port, () => { 
    console.log('Server is up and running on ' + port); 
}); 

這裏是我的路線文件:

//updated 
const routes = require('express').Router(); 


routes.get('/', (req, res) => { 
    res.render('home'); 
}); 



routes.post('/scan', (req, res) => { 
    res.status(200); 

    res.send("hello"); 
}); 



routes.get('/scanned', (req, res) => { 

    const orderID = req.params; 
    console.log(req); 

    res.render('home', { 
     orderID 
    }); 
}); 

module.exports = routes; 

當服務器運行起來,我要前往http://localhost:3000/scanned?orderid=234。我目前在routes.js文件中的控制檯日誌顯示一個空的主體(未識別URL中的orderid參數)。

回答

4

orderid中的請求是查詢參數。它需要通過req.query對象而不是req.params訪問。使用下面的代碼在請求中傳遞接入orderid

const orderID = req.query.orderid 

現在,你應該能夠得到請求URL傳遞234值。

或嘗試用以下替換代碼路徑/scanned

routes.get('/scanned', (req, res) => { 

    const orderID = req.query.orderid 
    console.log(orderID); // Outputs 234 for the sample request shared in question. 

    res.render('home', { 
    orderID 
    }); 
}); 
1

req.body不斷來了一個空的對象的原因是,在get請求,如通過導航瀏覽器發出,有是沒有身體的對象。在get請求中,查詢字符串包含您嘗試訪問的orderid。查詢字符串被附加到url。你的代碼可以如下改寫:

routes.get('/scanned', (req, res) => { 

    const orderID = req.query.orderid 
    console.log(req); 

    res.render('home', { 
     orderID 
    }); 
}); 

的說明,雖然是,如果你有AJAX的帖子你的客戶端代碼中激活,您req.body不會是空的,你可以解析它,你通常會。