简体   繁体   English

将数据从快速路由传递到节点模块 export function

[英]Pass data from express route into node module export function

I am new to node, I think I need to use middleware, but I can't warp my head around what it is actually used for, or if this is where it is meant to be used.我是 node 新手,我想我需要使用中间件,但我无法理解它的实际用途,或者它是否应该被使用。 I have data that is being posted from my view into an express route.我有从我的视图发布到快速路线的数据。

ROUTE - route.js路线 - route.js

 var GetPlayer = require('./models/getPlayer.js'); module.exports = function(app) { app.post('/api/getPlayer', function(req, res) { //GetPlayer.apiGetPlayer(req.body.username); console.log(req.body.username); //this logs the correct data }); }

but now I need to pass that data into a node api call and send that response back to the client.但现在我需要将该数据传递到节点 api 调用并将该响应发送回客户端。 But I can not get the route to call that function or pass the data into it.但我无法获得调用 function 或将数据传递给它的路线。

MODULE.EXPORT - getPlayer.js MODULE.EXPORT - getPlayer.js

 module.exports = { apiGetPlayer: function(error, res) { console.log("in get player"); console.log(res); } }

You would only want to use an Express middleware if this is something you want to do for more than one route (ie. parsing request body's from JSON to actual Object using body-parser ).如果您想对多个路由执行此操作(即使用body-parser将请求正文从 JSON 解析为实际 Object ),您只想使用 Express 中间件。 That seems like it could be overkill based on the supplied code.根据提供的代码,这似乎有点矫枉过正。 One way to approach this is to just take the username and pass a callback function in to getPlayer.解决此问题的一种方法是仅获取用户名并将回调 function 传递给 getPlayer。 Then when the callback function passed to apiGetPlayer() returns, respond back to the requester based on the result of apiGetPlayer() .然后当传递给apiGetPlayer()的回调 function 返回时,根据apiGetPlayer()的结果回复请求者。

getPlayer.js获取播放器.js

 module.exports = // callback is an error-first callback function apiGetPlayer: function(username, callback) { let err; let player; // Logic for getting player go here // If an error occurs return an error to the callback if (err) return callback(err, null); return callback(null, player); } }

/api/getPlayer route /api/getPlayer 路由

app.post('/api/getPlayer', (req, res) => { GetPlayer.apiGetPlayer(req.body.username, (err, player) => { if (err) return res.status(500).send(err); return res.status(200).send(player); }); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM