首页 > 解决方案 > 带有 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?

标签: javascriptnode.jssocket.io

解决方案


所以这里有很多事情不是我们需要解决的,我们边走边解释。

/*
 * 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);
}

我希望这能帮助你克服学习中的一些障碍,不过祝你好运。


推荐阅读