为什么路线没有在这里注册?出于某种原因,当我访问/ api / test时,我找不到404。当我在当时的功能之外移动路线注册时,它可以工作。此代码段是从快速生成的模板中的app.js添加的。
var Q = require('q');
promisify().then(stringText => {
var route = express.Router();
route.get('/test', (req, res) => res.send('Hi'));
app.use('/api', route);
});
function promisify() {
var deferred = Q.defer();
deferred.resolve('Hello World');
return deferred.promise;
}
这有效(如果你在外面移动路线注册):
var Q = require('q');
var route = express.Router();
route.get('/test', (req, res) => res.send('Hi'));
app.use('/api', route);
promisify().then(stringText => {
});
function promisify() {
var deferred = Q.defer();
deferred.resolve('Hello World');
return deferred.promise;
}
更新:重现的步骤
express
,在文件夹上创建快速模板。npm install
。npm install --save q
在注册其他路径的代码下方添加代码:
app.use('/', index);
app.use('/users', users);
// Add the code above here
答案 0 :(得分:0)
您是否在控制台中收到任何错误?如果没有你启动服务器?我试着做你的逻辑(在承诺内和承诺之外)我发现它使用http://localhost:3000/api/test下面的代码
1.Inside Promise Callback
const express = require('express');
const app = express();
const Q = require('q');
promisify().then(stringText => {
console.log("called promise success");
console.log(stringText);
var route = express.Router();
route.get('/test', (req, res) => res.send(stringText));
app.use('/api', route);
});
function promisify() {
const deferred = Q.defer();
if (true) deferred.resolve('Hello Chris James');
return deferred.promise;
}
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
2.Outside Promise回调
const express = require('express');
const app = express();
const Q = require('q');
var route = express.Router();
route.get('/test', (req, res) => res.send('Hi'));
app.use('/api', route);
promisify().then(stringText => {
});
function promisify() {
var deferred = Q.defer();
deferred.resolve('Hello World');
return deferred.promise;
}
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
});
的package.json
{
"name": "route-check",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start" : "node index.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.14.1",
"q": "^1.4.1"
}
}