我有一个这样的api:
app.get('/test', (req, res) => {
console.log("this is test");
});
Run Code Online (Sandbox Code Playgroud)
和另一个api:
app.get('/check', (req, res) => {
//I want to call "test" api without redirect to it.
});
Run Code Online (Sandbox Code Playgroud)
我想在“check”api中调用“test”api而不重定向到“test”api,只需在“test”api中执行函数即可。上面是示例代码。因为我不想将函数从“测试”api 重写为“检查”
简单的解决方案是定义一个可以使用两个请求路由调用的方法。
app.get('/test', (req, res) => {
console.log("this is test");
callMeMayBe();
});
callMeMayBe()
{
//Your code here
}
Run Code Online (Sandbox Code Playgroud)
要“从另一个 API 调用 API”,一种快速简便的方法是在 Express 服务器内发送 HTTP 请求,浏览器永远不会知道内部 HTTP 调用发生,更不用说页面重定向。这种设计的好处包括:
下面是一个例子:
var http = require('http');
router.get('/test', function(req, res) {
res.end('data_from_test');
});
router.get('/check', function(req, res) {
var request = http.request({
host: 'localhost',
port: 3000,
path: '/test',
method: 'GET',
headers: {
// headers such as "Cookie" can be extracted from req object and sent to /test
}
}, function(response) {
var data = '';
response.setEncoding('utf8');
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => {
res.end('check result: ' + data);
});
});
request.end();
});
Run Code Online (Sandbox Code Playgroud)
结果GET /check
将是:
check result: data_from_test
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9097 次 |
最近记录: |