我正在尝试建立一个Node.js server
可以同时满足http
和socket
请求的服务。
注意:我的server
和client
需要是两个独立的东西。我不是index.html
从server
. 我有一个单独的standalone
副本index.html
和socket.io.js
当我向它提出AJAX
请求时,server
它可以完美运行。但是当我尝试连接到server
with 时socket
,我得到一个error.
XMLHttpRequest cannot load http://localhost:3000/socket.io/?EIO=2&transport=polling&t=1401878926555-0. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.33' is therefore not allowed access.
我的服务器端代码
ar express = require('express.io');
var cors = require("cors");
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var gen = require('./public/javascripts/config');
gen.log("holla");
var app = express().http().io();
app.use(cors());
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
// development only
if ('development' === app.get('env')) {
app.use(express.errorHandler());
}
var parseCookie = require('connect').utils.parseCookie;
app.get('/', function(req, res) {
res.end("holla!");
});
app.post('/search', function(req, res) {
res = gen.setHeaders(res);
console.log('search segment hit');
res.end('search segment hit');
});
app.post('/opponent', function(req, res) {
res = gen.setHeaders(res);
console.log('opponent segment hit');
res.end('opponent segment hit');
});
app.io.route('ready', function(req) {
console.log(req.data);
req.io.emit('ready-ack', {data: "hahah"});
});
app.listen(3000);
console.log("Server Listening to Port 3000");
我的客户端代码 - Index.html
$(document).on('ready', function() {
var socket = io.connect("http://192.168.1.33:3000");
socket.emit("ready", {data:"client ready"});
socket.on('ready-ack', function(data) {
console.log(data);
});
$("#but").on('click',function(e){
e.preventDefault();
$.ajax({
url:"http://localhost:3000/search",
type:"POST",
success:function(data){
console.log("AJAX Data - "+data);
}
});
});
$("#tub").on('click',function(e){
e.preventDefault();
$.ajax({
url:"http://localhost:3000/opponent",
type:"POST",
success:function(data){
console.log("AJAX Data - "+data);
}
});
});
});