【发布时间】:2018-01-19 23:18:37
【问题描述】:
我正在关注this Node JS 教程,但我遇到了一个问题,我得到的是Cannot GET / 而不是Hello 的响应。这是我的代码的结构:
myapp/
├── app
│ └── routes
│ ├── index.js
│ └── note_routes.js
├── conf
│ ├── httpd-app.conf
│ └── httpd-prefix.conf
├── htdocs
├── node_modules
│ ├── ...
├── package.json
├── package-lock.json
└── server.js
server.js 看起来像这样:
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
require('./app/routes')(app, {});
app.listen(port, () => {
console.log('We are live on ' + port);
});
index.js是这个:
const noteRoutes = require('./note_routes');
module.exports = function(app, db) {
noteRoutes(app, db);
// Other route groups could go here, in the future
};
而note_routes.js 看起来像这样:
module.exports = function(app, db) {
app.post('/notes', (req, res) => {
// You'll create your note here.
res.send('Hello')
});
};
可以看出,这是一个非常简单的设置。根据上面链接的教程,这应该足够了,应该回复Hello。然而,这种情况并非如此。
我几乎 100% 确定端口是正确的,因为有 一些 非 503 响应。
这里出了什么问题,我怎样才能让它按预期工作?
【问题讨论】:
-
你必须使用 POST 而不是 GET
-
@DZDomi,
note_routes.js中的app.post(...)不这样做吗?我在哪里使用 get? -
将 app.post 行改为 app.get 即可在浏览器中调用
-
或者如果您使用的是邮递员(在教程中使用),您必须将下拉菜单中的 HTTP 方法从 GET 更改为 POST(取决于您想要什么)
-
并学习不同的http方法:developer.mozilla.org/en-US/docs/Web/HTTP/Methods
标签: javascript node.js server