我正在使用Laravel Lumen为我的MeteorJS App创建API。这是我在imports\api\tasks.js
...
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");
};
});
},
....
但是当我收到此错误时:
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 :(得分:0)
在你的server / main.js中试试这个
WebApp.rawConnectHandlers.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
return next();
});
答案 1 :(得分: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调用来完成此操作。
答案 2 :(得分:-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"
});