使用传递给express服务器的参数执行一个函数?
我想使用传递给快速调用的参数来调用一个函数。 下面是一个绑定在app.get()内调用一个简单的console.log的例子:
// server.js const express = require('express') const app = express() const port = process.env.PORT || 3001 function processRequest(api_key, another_value) { console.log(api_key, another_value) } app.get('/api', function(req, res) { let api_key = req.query.api_key let another_value = req.query.another_value processRequest(api_key, another_value) res.json({api_key, another_value}) }) app.listen(port) console.log("Started server")
和一个简单的testing
const axios = require('axios') function test() { axios.get('localhost:3001/api?api_key=testkey&another_value=anothervalue', res => console.log(res.data)) } test()
我知道我在这里错过了一些简单的东西。 谢谢你们
使用req.query.somevalue
从请求中获取查询参数。
req.param
只适用于像api/distance/:id
这样的URL参数
一些来自文档:
(req.params)检查路由参数,例如:/ user /:id
(req.query)检查查询string参数,例如:?id = 12检查urlencoded body params