javascript - 带有 socket.io 的 app.post 导致无法 GET
问题描述
我正在为我和我的朋友制作一个小应用程序,但由于某种原因它无法正常工作。我对socket.io还很陌生,所以我自己无法弄清楚......所以我正在使用这个服务器端代码:
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post('/initiate', (request, response) => {
console.log("yey1");
const { body } = request;
initiate(body.command);
});
http.listen(3000, () => {
console.log('Listening on port 3000');
});
function initiate(command){
console.log("yey");
io.emit("command", command);
}
app.use(bodyParser.urlencoded({ extended: false }));
app.set('views', __dirname + '/public');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.get('/', (req, res) => {
res.render(__dirname + '/public/index.html', {command: "Awaiting..."});
});```
And whenever you try to connect to <url>/initiate, it just says ```cannot GET /initiate```.
What am I doing wrong?
解决方案
所以这里有很多事情不是我们需要解决的,我们边走边解释。
/*
* So first thing you need to understand is Express or HTTP is a static server, so this
* means that once you start it or call the listen function, you cant really change
* anything after that, so you want to configure all your routes properly before calling
* the listen function.
*/
// use const because its not like your gonna reinstantiate these anytime soon
const bodyParser = require('body-parser');
const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
app.use(bodyParser.json());
// This route has to be configured first because if you define it last, it will
// overwrite the initiate route that you have.
app.get('/', (req, res) => {
res.render(__dirname + '/public/index.html', {command: "Awaiting..."});
});
// The reason you're getting the GET error when browsing to it is because this route,
// has been configured to use the POST method so if you want it to be accessible on a
// GET method then use app.get
app.get('/initiate', (request, response) => {
console.log("yey1");
const { body } = request;
initiate(body.command);
});
app.set('views', __dirname + '/public');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(bodyParser.urlencoded({ extended: false }));
// So you see, you have to setup the whole server first before starting it up
http.listen(3000, () => {
console.log('Listening on port 3000');
});
function initiate(command){
console.log("yey");
io.emit("command", command);
}
我希望这能帮助你克服学习中的一些障碍,不过祝你好运。
推荐阅读
- swift - Flickr 照片上传不适用于 OAtuth1Swift postImage 方法
- java - 从java中的项目文件夹(不是bin)加载图像
- c++ - Compound assignment E1 op= E2 is not equivalent to E1 = E1 op E2
- c# - 如何将解析存储的字符串从数据库反转为浏览器理解的 HTML 标记?
- pandas - 熊猫逐列删除重复值
- ionic-framework - 如何从科尔多瓦离子应用程序中的一个信号附加数据对象访问数据
- java - RecyclerView Android 不显示 Gson 响应的任何结果
- php - 如何从php中的对象获取国家代码?
- lua - 为什么将一个表作为值分配给另一个表会导致问题?
- fortran - 用 MVAPICH2 编译 Fortran 2003 程序