2017-03-23 45 views
0

我正在使用Laravel Lumen爲我的MeteorJS應用程序創建一個API。這是imports\api\tasks.jsMeteorJS中的'Access-Control-Allow-Origin'錯誤

... 
import { HTTP } from 'meteor/http'; 
import { WebApp } from 'meteor/webapp'; 

if (Meteor.is_client) { 

    // Calling our Meteor server's function 
    // and simply storing data into current session 
    Meteor.call('fetchDataFromUrl', function (error, response) { 
     Session.set('external_server_data', response) 
    }); 


    // Providing meteor data for template (it renders on data received) 
    Template.data.server_data = function() { 
     return Session.get('external_server_data'); 
    }; 

} 

if (Meteor.is_server) { 

    Meteor.methods({ 
     // Declaring a method 
     retrieve_doc_types: function() { 
      this.unblock(); 
      return Meteor.http.get(api_url); 
     } 
    }); 

} 

Meteor.methods({ 

    'tasks.insert'(make, model, year) { 
    check(make, String); 
    check(model, String); 
    check(year, String); 

    if (! Meteor.userId()) { 
     throw new Meteor.Error('not-authorized'); 
    } 

    HTTP.call("POST", "http://localhost:8000/api/v1/car", 
      {data: {"make":make, "model":model, "year":year}}, 
     function (error, result) { 

      if (!error) { 
       console.log(result); 
      } else{ 

       console.log("http post error"); 
      }; 
     }); 
    }, 

.... 

我的代碼INMŸmeteorJS但是當我得到這個錯誤:

XMLHttpRequest cannot load http://localhost:8000/api/v1/car. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 405. 
tasks.js:81 http post error 

做的人有一個想法?我是新與MeteorJS

回答

0

試試這個在您的服務器/ main.js

WebApp.rawConnectHandlers.use(function(req, res, next) { 
    res.setHeader("Access-Control-Allow-Origin", "*"); 
    return next(); 
}); 
+0

我仍然有錯誤 – gadss

+0

你使用nginx嗎? – mutdmour

+0

我正在使用我的筆記本電腦,我使用XAMPP,Windows 10操作系統 – gadss

-1

有人想答案,但我沒有得到它。你試試你的運氣。 https://codexample.org/questions/9358/no-access-control-allow-origin-error-in-meteor-app.c

 Try package - simple:json-routes and put following code at serverside startup. 
    // Enable cross origin requests for all endpoints 
    JsonRoutes.setResponseHeaders({ 
     "Cache-Control": "no-store", 
     "Pragma": "no-cache", 
     "Access-Control-Allow-Origin": "*", 
     "Access-Control-Allow-Methods": "GET, PUT, POST, DELETE, OPTIONS", 
     "Access-Control-Allow-Headers": "Content-Type, Authorization, X-Requested-With" 
    }); 
0

你在哪裏調用該方法?該方法稱爲tasks.insert,但您提供的代碼僅調用fetchDataFromUrl方法。

這裏有一些想法。

  • 檢查您的客戶端呼叫是異步使用的。從Metor HTTP文檔:On the client, this function must be used asynchronously by passing a callback. Note that some browsers first send an OPTIONS request before sending your request (in order to determine CORS headers).

  • 我的CORS問題也在我的項目之一,我最終只使用HTTP庫服務器端。您可以通過使用Meteor.isServer來實現HTTP呼叫。