![](/img/trans.png)
[英]Calling a variable to a different route not working in nodejs and express
[英]Calling Express Route internally from inside NodeJS
我的 API 有一个 ExpressJS 路由,我想从 NodeJS 中调用它
var api = require('./routes/api')
app.use('/api', api);
在我的./routes/api.js文件中
var express = require('express');
var router = express.Router();
router.use('/update', require('./update'));
module.exports = router;
所以如果我想从我的前端调用/api/update/something/:withParam
它所有的发现,但我需要从我的 NodeJS 脚本的另一个方面调用它,而不必在第二个位置再次重新定义整个函数
我尝试从内部使用 HTTP 模块,但我只是收到“ECONNREFUSED”错误
http.get('/api/update/something/:withParam', function(res) {
console.log("Got response: " + res.statusCode);
res.resume();
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
我了解 Express 背后的想法是创建路线,但我如何在内部调用它们
处理此问题的“通常”或“正确”方法是让您要调用的函数自行中断,与任何路由定义分离。 也许在它自己的模块中,但不一定。 然后在需要的地方调用它。 像这样:
function updateSomething(thing) {
return myDb.save(thing);
}
// elsewhere:
router.put('/api/update/something/:withParam', function(req, res) {
updateSomething(req.params.withParam)
.then(function() { res.send(200, 'ok'); });
});
// another place:
function someOtherFunction() {
// other code...
updateSomething(...);
// ..
}
这是在Express 4中进行内部重定向的一种简单方法:
魔术能做的功能是: app._router.handle()
测试:我们向home "/"发出请求并将其重定向到otherPath "/other/path"
var app = express()
function otherPath(req, res, next) {
return res.send('ok')
}
function home(req, res, next) {
req.url = '/other/path'
/* Uncomment the next line if you want to change the method */
// req.method = 'POST'
return app._router.handle(req, res, next)
}
app.get('/other/path', otherPath)
app.get('/', home)
我为此制作了一个专用的中间件: uest
。
在req
中可用,它允许您req.uest
另一条路线(来自给定路线)。
它将原始 cookie 转发给后续请求,并在请求之间保持req.session
同步,例如:
app.post('/login', async (req, res, next) => {
const {username, password} = req.body
const {body: session} = await req.uest({
method: 'POST',
url: '/api/sessions',
body: {username, password}
}).catch(next)
console.log(`Welcome back ${session.user.firstname}!`
res.redirect('/profile')
})
它支持 Promise、await 和 error-first 回调。
有关更多详细信息,请参阅自述文件
将您的应用程序和服务器文件与要导入服务器文件的应用程序分开。
在您想在内部调用您的应用程序的地方,您可以导入您的应用程序以及来自“supertest”的“请求”。 然后你可以写
request(app).post('/someroute').send({
id: 'ecf8d501-5abe-46a9-984e-e081ac925def',
etc....
});`
这是另一种方式。
const app = require('express')()
const axios = require('axios')
const log = console.log
const PORT = 3000
const URL = 'http://localhost:' + PORT
const apiPath = (path) => URL + path
app.get('/a', (req, res) => {
res.json('yoy')
})
app.get('/b', async (req, res) => {
let a = await axios.get(apiPath('/a'))
res.json(a.data)
})
app.listen(PORT)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.