I'm working on a app with socket.io, ejs, express & nginx on a Node JS server.
I have managed to get the socket.io working withthout use of ejs
.
But when I try to implement it with ejs
I get error 400
on client.js
.
Here is my code for server.js
:
var express = require('express');
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var ejs = require('ejs');
// WITHOUT EJS : WORKS FINE
app.get('/', function(req, res) {
res.sendFile(index.html');
});
// WITH EJS : GET HTTP ERR 400 IN CLIENT.JS CONSOLE
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render('pages/index');
});
io.on('connection', function(socket) {
console.log('a user connected');
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});
server.listen(process.env.PORT || 8080, function(){
console.log('app running');
});
My nginx
code looks like this :
# HTTP — redirect all traffic to HTTPS
server {
listen 80;
listen [::]:80 default_server ipv6only=on;
return 301 https://$host$request_uri;
}
# HTTPS — proxy all requests to the Node app
server {
# Enable HTTP/2
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com;
# Use the Let’s Encrypt certificates
ssl_certificate /.../;
ssl_certificate_key /.../;
location ~* .io {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy false;
proxy_pass http://example.com:8080;
proxy_redirect off;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
Here is my client.js
:
var socket = io();
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
What could be the issue here ?
question from:
https://stackoverflow.com/questions/65897231/using-socket-io-with-ejs-on-express-nginx 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…