Enable cross-origin resource sharing in Meteor? - javascript

I'm trying to get a list of channels from my main application to an external angular app.
I've added https://github.com/stubailo/meteor-rest/blob/master/packages/rest/README.md to my main meteor app and now I can get the collection with a url as json format.
Now the problem comes when I try to http request from the external angular app.
Here's what I have in my main meteor app:
'use strict'
Meteor.publish('channels', function (index) {
return Channels.find({});
}, {
url: 'channels',
httpMethod: 'get'
});
and here's what I use to make the http request in the external angular app:
// Simple GET request example:
$http.get('http://example.com/channels').then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
console.log('success');
console.log(response);
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log('error');
console.log(response);
});
But what I get in response is an error:
XMLHttpRequest cannot load http://example.com/channels. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
What can I do to fix this?

From the documentation on the meteor-rest package:
If you would like to use your API from the client side of a different app, you need to return a special header. You can do this by hooking into a method on the simple:json-routes package, like so:
// 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"
});

Related

Axios get request with CORS not working in laravel 5.5

I'm using Reactjs with Laravel5.5 i'm working with League of legends API (Riot API), i want to send a get requests to retrieve some JSON data summoner name, summoner id etc...
i tried to send a normal axios get request inside my app.js like this one:
axios.get('/url_of_api').then(function (response){
console.log(response.data);
});
but i got this error:
ailed to load https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-name/skt%20ayech0x2?api_key=my_api_key: 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:8000' is therefore not allowed access. The response had HTTP status code 405.
Even i tried to add a custom header requests to my axios
let config = {
headers: {
"Origin": null,
"Accept-Charset": "application/x-www-form-urlencoded; charset=UTF-8",
"X-Riot-Token": "my_api_key",
"Accept-Language": "en-US,en;q=0.5",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0"
}
}
axios.post('url_of_api',config).then(function (response){
console.log(response.data);
});
I'm facing the same problem, but i found a solution with creating a new Laravel middleware and adding this code into it
<?php
namespace App\Http\Middleware;
use Closure;
class Cors {
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
So with this route i get the response
Route::get('/lol', ['middleware' => 'cors', function()
{
$unparsed_json = file_get_contents("https://euw1.api.riotgames.com /lol/summoner/v3/summoners/by-name/skt%20ayech0x2?api_key=my_api_key");
$json_object = json_decode($unparsed_json);
return response()->json($json_object);
}]);
But i want to make it with axios please any suggest? thanks in advance guys.
Riot Games API v3 doesn't support CORS anymore.*
You will need to make those calls from your server.**

Getting the HTML source of a page in NodeJS

I'm currently struggling to get the HTML source of a webpage in NodeJS due to cors restrictions. Using JQuery I'm making a GET request to a page expecting an HTML response. This however throws the error XMLHttpRequest cannot load https://www.reddit.com/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8000' is therefore not allowed access. Is there a way to bypass CORS using NodeJS? (like via proxy)
$.ajax({
url: 'https://www.reddit.com/',
headers: {
'Content-Type': 'text/html',
"Access-Control-Allow-Origin": '*'
},
type: "GET",
data: {
},
success: function (result) {
console.log(result);
},
error: function () {
console.log("error");
}
});
I'm also using webpack dev server with the following headers
headers: {
"Access-Control-Allow-Origin": '*',
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS"
}
Do not use jquery in nodejs, you can use this libs to archieve what you need:
isomorphic-fetch
request
Hope it helps

Microsoft Cognitive Services JavaScript Request 'Access-Control-Allow-Origin'

Hy, when I try to access the Microsoft Cognitive Services API via JavaScript from my server/local machine I get the following error.
XMLHttpRequest cannot load http://api.projectoxford.ai/vision/v1.0/analyze?visualFeatures=Categories. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myUrl.com' is therefore not allowed access. The response had HTTP status code 401.
This is my request code:
function requestAPI(){
var params = {
// Request parameters
"visualFeatures": "Categories"
};
$.ajax({
url: "http://api.projectoxford.ai/vision/v1.0/analyze?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{myKey}");
},
type: "POST",
// Request body
data: "{'url':'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg'}",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
}
In my .htaccess I already added:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
When I test the request with hurl.it it works. Just from my server it doesn't.
Looks like you are setting CORS headers for your server which means someone can make cross-domain request to your server.
Microsoft Cognitive Services have to add these headers on their server so that you can make cross-domain request to them or you have to use JSONP.

Cannot authenticate into BigCommerce API because of CORS

I want to make API calls into the BigCommerce API (https://developer.bigcommerce.com/api) using the Basic Authentication.
My AJAX call looks like following:
$.ajax({
type: 'GET',
url: 'https://store-zkk8z5i.mybigcommerce.com/api/v2/products',
xhrFields: {
withCredentials: true
},
headers: {
'Authorization': 'Basic ' + MY_TOKEN,
'Accept': 'application/json'
},
success: function (event) {
debugger
},
error: function (error) {
debugger
}
});
But I keep getting the following error:
XMLHttpRequest cannot load
https://store-zkk8z5i.mybigcommerce.com/api/v2/products. Response to
preflight request doesn't pass access control check: A wildcard '*'
cannot be used in the 'Access-Control-Allow-Origin' header when the
credentials flag is true. Origin
'http://store-zkk8z5i.mybigcommerce.com' is therefore not allowed
access. The credentials mode of an XMLHttpRequest is controlled by the
withCredentials attribute.
I'm pretty sure that my credentials are okay because I get successful responses when I make my requests using cURL.
Any ideas?
I'm pretty sure that my credentials are okay
That's rather beside the point. Look at the error message:
A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true.
Since you are sending credentials, you can't use a wildcard for Access-Control-Allow-Origin.
You have to say Access-Control-Allow-Origin: http://store-zkk8z5i.mybigcommerce.com and not Access-Control-Allow-Origin: *.

AngularJS: Cannot send POST request with appropiate CORS headers

I'm creating a web app using AngularJS. To test it, I'm running the app in a NodeJS server, using angular-seed template.
In this app, I need to send a JSON message to another host, via POST request, and get the response, so, I'm using CORS.
My request is done by implementing a service that uses AngularJS http service (I need the level of abstraction that $http provides. So, I don't use $resource).
Here, my code. Please pay attention to the fact that I modify $httpProvider to tell AngularJS to send its requests with the appropriate CORS headers.
angular.module('myapp.services', []).
// Enable AngularJS to send its requests with the appropriate CORS headers
// globally for the whole app:
config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
/**
* Just setting useXDomain to true is not enough. AJAX request are also
* send with the X-Requested-With header, which indicate them as being
* AJAX. Removing the header is necessary, so the server is not
* rejecting the incoming request.
**/
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]).
factory('myService', function($http) {
return {
getResponse: function() {
var exampleCommand = JSON.stringify({"foo": "bar"});
// This really doesn't make a difference
/*
var config = {headers: {
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Headers': 'Content-Type, Content-Length, Accept',
'Content-Type': 'application/json'
}
};
*/
//return $http.post(REMOTE_HOST, exampleCommand, config).
return $http.post(REMOTE_HOST, exampleCommand).
success(function(data, status, headers, config) {
console.log(data);
return data;
}).
error(function (data, status, headers, config) {
return {'error': status};
});
}
}
});
The problem is I can't make it work. I always get this error message:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at REMOTE_HOST. This can be fixed by moving the
resource to the same domain or enabling CORS.
But if I do a simple jQuery AJAX call like this:
$.ajax(REMOTE_HOST,
{
dataType: "json",
type: "POST",
data: exampleCommand,
success: function(data) { console.log(data); },
error: function(request, textStatus, errorThrown) { console.log("error " + textStatus + ": " + errorThrown);}
});
It works fine.
So, my questions:
- How do I allow cross-site requests in an AngularJS running under NodeJS?
UPDATE: Thanks to Dayan Moreno Leon's response.
My problem is I need to add cors support to my server. I'm using NodeJS http-server for development and lighttpd for production.
- Why does the simple jQuery POST request work but AngularJS POST request doesn't?
I guess jQuery AJAX requests are cross-domain by default. Not really sure yet.
Many thanks in advance
CORS is not handled on the client but in the server you need to allow CORS on your nodejs app where your angular app is trying to POST. you can try using cors module if you are using express
https://www.npmjs.org/package/cors
other whise you need to check for the options method and return 200 as a response
http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
Why does the simple jQuery POST request work but AngularJS POST request doesn't?
jQuery uses simple requests while AngularJS uses preflighted requests
In your angular code you can add set Content-Type to application/x-www-form-urlencoded and encode your data using $.param

Categories

Resources