I am having an hard time making server and client interact.
Here is the relevant code:
var mongodb = require('mongodb');
var fs = require('fs');
var http = require('http');
var express = require('express');
var io = require('socket.io');
var cors = require('cors');
var app = express();
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
app.use(express.static('./public'));
app.get('/', function(req, res) {
res.send('/index.html')
});
var server = http.createServer(app)
io = io.listen(server);
server.listen(8000);
The website loads the io.js script with:
<script src="http://localhost:8000/socket.io/socket.io.js"></script>
If I remove the port number I get a plain not found error and undefined io.
However, I get the following error, in Chrome:
GET http://localhost/socket.io/?EIO=3&transport=polling&t=1441274392959-0
XMLHttpRequest cannot load http://localhost/socket.io/?EIO=3&transport=polling&t=1441274392959-0. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. The response had HTTP status code 404.
In Firefox:
GET XHR http://localhost/socket.io/ [HTTP/1.0 404 Not Found 2ms]
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/socket.io/?EIO=3&transport=polling&t=1441275119628-17. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
Searching for the Cross-Origin error, I tried a couple of sulutions:
The setHeader section I used in the code,
https://stackoverflow.com/a/21622564 tried on app, server and io.
Neither of them worked, and I don't understand why.
Can someone help me sort this out? Thanks.