1

Node.js serverと の両方httpsocketリクエストに対応できるを確立しようとしています。

注: Myserverclientは 2 つの別個のものである必要があります。私は からサービスを提供index.htmlしていませんserver。との別のstandaloneコピーがindex.htmlありますsocket.io.js

AJAXリクエストすると、server完全に機能します。serverしかし、 withに接続しようとするとsocketerror.

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

            });
4

0 に答える 0