Oliver L
Oliver L

Reputation: 23

app.post with socket.io results in cannot GET

I'm making a little app for me and my friends, but it isn't working for some reason. I'm pretty new to socket.io so I couldn't figure it out on my own... So I'm using this server-side code:

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?

Upvotes: 0

Views: 154

Answers (1)

bloo
bloo

Reputation: 1560

so there are quite a couple things that arent right here that we will need to fix, ill explain as we go.

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

I hope this helps getting you past some of the hurdles in your learning, good luck though.

Upvotes: 1

Related Questions