2013-12-24 3 views
30

Immer wenn ich eine Webapp mache und ich ein CORS-Problem bekomme, beginne ich Kaffee zu machen. Nachdem ich mich eine Weile damit beschäftigt habe, schaffe ich es, aber dieses Mal ist es nicht und ich brauche Hilfe. Hier

ist der Client-Seite Code:

$http({method: 'GET', url: 'http://localhost:3000/api/symbol/junk', 
      headers:{ 
       'Access-Control-Allow-Origin': '*', 
       'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 
       'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With', 
       'X-Random-Shit':'123123123' 
      }}) 
     .success(function(d){ console.log("yay"); }) 
     .error(function(d){ console.log("nope"); }); 

Die Server-Seite ist eine regelmäßige node.js mit einer ausdrücklichen App. Ich habe eine Erweiterung namens cors und es wird auf diese Weise mit Express verwendet:

var app = express(); 
app.configure(function(){ 
    app.use(express.bodyParser()); 
    app.use(app.router); 
    app.use(cors({origin:"*"})); 
}); 
app.listen(3000); 

app.get('/', function(req, res){ 
    res.end("ok"); 
}); 

Wenn ich

curl -v -H "Origin: https://github.com" http://localhost:3000/ 

Es wird wieder mit:

* Adding handle: conn: 0x7ff991800000 
* Adding handle: send: 0 
* Adding handle: recv: 0 
* Curl_addHandleToPipeline: length: 1 
* - Conn 0 (0x7ff991800000) send_pipe: 1, recv_pipe: 0 
* About to connect() to localhost port 3000 (#0) 
* Trying ::1... 
* Trying 127.0.0.1... 
* Connected to localhost (127.0.0.1) port 3000 (#0) 
> GET/HTTP/1.1 
> User-Agent: curl/7.30.0 
> Host: localhost:3000 
> Accept: */* 
> Origin: https://github.com 
> 
< HTTP/1.1 200 OK 
< X-Powered-By: Express 
< Date: Tue, 24 Dec 2013 03:23:40 GMT 
< Connection: keep-alive 
< Transfer-Encoding: chunked 
< 
* Connection #0 to host localhost left intact 
ok 

Wenn ich die Client-Seite ausgeführt Code, es brigt diesen Fehler auf:

OPTIONS http://localhost:3000/api/symbol/junk No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. angular.js:7889 
XMLHttpRequest cannot load http://localhost:3000/api/symbol/junk. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. localhost/:1 
nope 

Prüfen Chromes Header:

Request URL:http://localhost:3000/api/symbol/junk 
Request Method:OPTIONS 
Status Code:200 OK 
Request Headersview source 
Accept:*/* 
Accept-Encoding:gzip,deflate,sdch 
Accept-Language:en-US,en;q=0.8,es;q=0.6,pt;q=0.4 
Access-Control-Request-Headers:access-control-allow-origin, accept, access-control-allow-methods, access-control-allow-headers, x-random-shit 
Access-Control-Request-Method:GET 
Cache-Control:max-age=0 
Connection:keep-alive 
Host:localhost:3000 
Origin:http://localhost:8000 
Referer:http://localhost:8000/ 
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36 
Response Headersview source 
Allow:GET 
Connection:keep-alive 
Content-Length:3 
Content-Type:text/html; charset=utf-8 
Date:Tue, 24 Dec 2013 03:27:45 GMT 
X-Powered-By:Express 

Überprüfung der Anfrage-Header Ich sehe, dass mein Test-String X-Zufall Scheiße vorhanden ist in den "Access-Control-Request-Header", aber es ist Wert nicht da ist. In meinem Kopf habe ich auch erwartet, dass ich für jeden der Header, die ich einstelle, eine Zeile sehe, keinen Blob.

UPDATES ---

änderte ich meine Frontend jQuery anstelle von Winkel- und machte mein Backend wie folgt aus:

var app = express(); 
app.configure(function(){ 
    app.use(express.bodyParser()); 
    app.use(app.router); 
}); 
app.all('*', function(req, res, next) { 
    res.header("Access-Control-Allow-Origin", "*"); 
    res.header('Access-Control-Allow-Methods', 'OPTIONS,GET,POST,PUT,DELETE'); 
    res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With"); 
    if ('OPTIONS' == req.method){ 
     return res.send(200); 
    } 
    next(); 
}); 

app.get('/', function(req, res){ 
    res.end("ok"); 
}); 

es mit GET funktioniert jetzt aber nicht mit irgendetwas anderes (PUT , POST ..).

Ich werde sehen, wenn jemand von Ihnen mit einer Lösung kommt. In der Zwischenzeit das RESTful-Konzept aus dem Fenster werfen und alles mit GETs machen.

+0

Kaffee löst viele Probleme ... = ~) – HaveSpacesuit

Antwort

4

Ich hatte Erfolg mit Express-und Bearbeitung der res.header. Mine passt Ihnen ziemlich eng, aber ich habe eine andere Allow-Headers wie unten angegeben:

res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 

Ich bin auch Winkel- und Node/Express verwenden, aber ich habe nicht die einzigen der Knoten in der Angular-Code genannt Header aus/express

1

unten server.js Hinzufügen Mine

server.post('/your-rest-endpt/*', function(req,res){ 
    console.log(''); 
    console.log('req.url: '+req.url); 
    console.log('req.headers: '); 
    console.dir(req.headers); 
    console.log('req.body: '); 
    console.dir(req.body); 

    var options = { 
     host: 'restAPI-IP' + ':' + '8080' 

     , protocol: 'http' 
     , pathname: 'your-rest-endpt/' 
    }; 
    console.log('options: '); 
    console.dir(options); 

    var reqUrl = url.format(options); 
    console.log("Forward URL: "+reqUrl); 

    var parsedUrl = url.parse(req.url, true); 
    console.log('parsedUrl: '); 
    console.dir(parsedUrl); 

    var queryParams = parsedUrl.query; 

    var path = parsedUrl.path; 
    var substr = path.substring(path.lastIndexOf("rest/")); 
    console.log('substr: '); 
    console.dir(substr); 

    reqUrl += substr; 
    console.log("Final Forward URL: "+reqUrl); 

    var newHeaders = { 
    }; 

    //Deep-copy it, clone it, but not point to me in shallow way... 
    for (var headerKey in req.headers) { 
     newHeaders[headerKey] = req.headers[headerKey]; 
    }; 

    var newBody = (req.body == null || req.body == undefined ? {} : req.body); 

    if (newHeaders['Content-type'] == null 
      || newHeaders['Content-type'] == undefined) { 
     newHeaders['Content-type'] = 'application/json'; 
     newBody = JSON.stringify(newBody); 
    } 

    var requestOptions = { 
     headers: { 
      'Content-type': 'application/json' 
     } 
     ,body: newBody 
     ,method: 'POST' 
    }; 

    console.log("server.js : routes to URL : "+ reqUrl); 

    request(reqUrl, requestOptions, function(error, response, body){ 
     if(error) { 
      console.log('The error from Tomcat is --> ' + error.toString()); 
      console.dir(error); 
      //return false; 
     } 

     if (response.statusCode != null 
       && response.statusCode != undefined 
       && response.headers != null 
       && response.headers != undefined) { 
      res.writeHead(response.statusCode, response.headers); 
     } else { 
      //404 Not Found 
      res.writeHead(404);   
     } 
     if (body != null 
       && body != undefined) { 

      res.write(body);    
     } 
     res.end(); 
    }); 
}); 
8

ich AngularJS bin neu aufgelöst und ich kam in dieses Problem CORS, verlor fast den Verstand! Glücklicherweise habe ich einen Weg gefunden, dies zu beheben. Also hier geht es ....

Mein Problem war, wenn ich AngularJS $ Ressource beim Senden API Anfragen ich bekomme diese Fehlermeldung XMLHttpRequest cannot load http://website.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. Yup, ich habe bereits Callback = "JSON_CALLBACK" und es hat nicht funktioniert .

Was ich getan habe, um das Problem zu beheben, anstatt GET-Methode oder $ http.get verwenden, habe ich JSONP verwendet. Ersetzen Sie einfach die GET-Methode durch JSONP und ändern Sie auch das API-Antwortformat auf JSONP.

myApp.factory('myFactory', ['$resource', function($resource) { 

      return $resource('http://website.com/api/:apiMethod', 
         { callback: "JSON_CALLBACK", format:'jsonp' }, 
         { 
          method1: { 
           method: 'JSONP', 
           params: { 
              apiMethod: 'hello world' 
             } 
          }, 
          method2: { 
           method: 'JSONP', 
           params: { 
              apiMethod: 'hey ho!' 
             } 
          } 
      }); 

    }]); 

Ich hoffe, jemand findet dies hilfreich. :)

+0

Hinzufügen JSONP mein Problem –

1

Schreiben dieser Middleware könnte helfen!

app.use(function(req, res, next) { 
res.header("Access-Control-Allow-Origin", "*"); 
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,  Content-Type, Accept"); 
next(); 
}); 

für Details besuchen http://enable-cors.org/server_expressjs.html

0

ich einen Weg gefunden habe JSONP Verfahren in $http direkt zu verwenden und mit Unterstützung von params in dem Config-Objekt:

params = { 
    'a': b, 
    'callback': 'JSON_CALLBACK' 
}; 

$http({ 
    url: url, 
    method: 'JSONP', 
    params: params 
}) 
-1

mit Try this:

  $.ajax({ 
       type: 'POST', 
       url: URL, 
       defaultHeaders: { 
        'Content-Type': 'application/json', 
        "Access-Control-Allow-Origin": "*", 
        'Accept': 'application/json' 
       }, 

       data: obj, 
       dataType: 'json', 
       success: function (response) { 
      // BindTableData(); 
       console.log("success "); 
       alert(response); 
       }, 
       error: function (xhr) { 
       console.log("error "); 
       console.log(xhr); 
       } 
      }); 
+0

ein wenig Kontext gelöst? Fügen Sie eine Beschreibung Ihrer Lösung hinzu – PyNoob

1

@Swapnil Niwane

Ich konnte dieses Problem lösen, indem ich eine Ajax-Anfrage aufruft und die Daten nach 'jsonp' formatiere.

$.ajax({ 
      method: 'GET', 
      url: url, 
      defaultHeaders: { 
       'Content-Type': 'application/json', 
       "Access-Control-Allow-Origin": "*", 
       'Accept': 'application/json' 
      }, 

      dataType: 'jsonp', 

      success: function (response) { 
      console.log("success "); 
      console.log(response); 
      }, 
      error: function (xhr) { 
      console.log("error "); 
      console.log(xhr); 
      } 
});