我正在尝试使用socket.io和node构建登录系统。但是我不断收到错误
跨域请求被阻止:“同源起源”策略禁止读取http://127.0.0.1:4000/socket.io/?EIO=3&transport=polling&t=MShU2AZ处的远程资源。 (原因:CORS请求未成功。)
我已经用npm安装了cors,但是似乎无法正常工作,有人偶然知道我在做什么错吗?
谢谢您的时间。
server.js
var express = require('express');
const app = require('express')()
const mongo = require('mongodb').MongoClient;
const port = 3000;
const http = require('http').Server(app);
const client = require('socket.io').listen(http);
var mongoose = require('mongoose');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var cors = require('cors');
var path = require('path');
app.use(cors({credentials: true, origin: true}))
//set app to use ejs
app.set('view engine', 'ejs')
// set views dir for ejs
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// serve static files from template
app.use(express.static(__dirname + '/'));
// include routes
var routes = require('./routes/router');
app.use('/', routes);
// Connect to mongo
mongoose.connect('...', function(err, db) {
if (err) {
throw err;
}
// Set db log connection wass success
var db = mongoose.connection;
console.log('MongoDB connected...');
///////////////////////// not sure if needed
//use sessions for tracking logins
app.use(session({
secret: 'work hard',
resave: false,
saveUninitialized: true,
store: new MongoStore({
mongooseConnection: db
})
}));
///////////////////////////////
// Connect to Socket.io
client.on('connection', function(socket) {
//Retrieve user model
var userModel = require('./models/user');
// Handle user registration
socket.on('register', function(data) {
console.log(data.Username);
//The data that will get sent.
var newUser = userModel({
Username: data.Username,
Password: data.Password
})
// Save new user data
newUser.save(function(err) {
console.log("New user registered");
})
});
// Handle user login
socket.on('login', function(data) {
// console.log(data.Username);
// ["I'm the data that will get sent."
usernameFindMe = data.Username;
passwordFindMe = data.Password;
userModel.findOne({
Username: usernameFindMe,
Password: passwordFindMe
}, function(err, user) {
if (err) {
console.log('err');
}
if (!user) {
console.log('OH NOOOOOOOOOO');
} else {
console.log('yay');
module.exports.yourUserName = usernameFindMe;
var destination = '/';
client.emit('redirect', destination);
}
})
});
});
});
//Start the Server
http.listen(port, function() {
console.log('listening on *:' + port);
});
router.js
var express = require('express');
var router = express.Router();
//get variables from server
var sourceFile = require('./../server');
// Default Variables
userName = 'Not Logged In';
// GET route for dashboard
router.get('/', function(req, res, next) {
res.render('index.ejs', {
});
// set variables
function setRandom() {
if (sourceFile.yourUserName == null){
userName = 'Not Logged In';
}
else{
userName = sourceFile.yourUserName;
console.log(userName);
}
}
setRandom();
setInterval(setRandom, 200);
});
// GET route for dashboard
router.get('/register', function(req, res, next) {
res.render('register.ejs', {
});
// set variables
userName = sourceFile.yourUserName;
// log username for development
console.log(userName);
});
module.exports = router;
index.ejs
<div>
Register
<input type="text" id="usernameRegister" class="form-control" placeholder="Enter name...">
<input type="text" id="passwordRegister" class="form-control" placeholder="EnterPassword...">
<button id="userRegister" class="btn btn-danger" onclick="setTimeout(RegisterRedirect, 100)">Register</button>
</div>
<script>
// redirect from register page back to the login page for browsers
function RegisterRedirect() {
window.location.href = "/";
}
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script>
<script>
(function() {
var element = function(id) {
return document.getElementById(id);
}
//client side socket.io
// Get Elements
var UserRegister = element('userRegister')
var UserLogin = element('userLogin');
// Connect to socket.io
var socket = io({transports: ['websocket'], upgrade: false});
// Check for connection
if (socket !== undefined) {
console.log('Connected to socket...');
// Handle Register
UserRegister.addEventListener('click', function() {
socket.emit('register', {
Username: usernameRegister.value,
Password: passwordRegister.value
})
});
// Handle Login
UserLogin.addEventListener('click', function() {
socket.emit('login', {
Username: usernameLogin.value,
Password: passwordLogin.value
})
});
socket.on('redirect', function(destination) {
setTimeout(function() {
window.location.href = destination;
}, 300);
});
}
})();
</script>
变化中 var socket = io.connect('http://127.0.0.1:3000'); 至 var socket = io({transports:['websocket'],upgrade:false}); 解决了问题