Rails doesn't work with restangular - ruby-on-rails

I'm trying to get some data from JSON via Angular, but getting this error
XMLHttpRequest cannot load http://localhost:3000/movies.json. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://blabla.herokuapp.com' is therefore not
allowed access.
But I have this config and there is right host:
var app = angular.module('Test', ['restangular'])
.config(function (RestangularProvider) {
RestangularProvider.setBaseUrl("http://blabla.herokuapp.com");
RestangularProvider.setRequestSuffix('.json');
RestangularProvider.setDefaultHttpFields({xsrfCookieName:'csrftoken', xsrfHeaderName:'X-CSRFToken'});
});
On the local machine this works fine(if I replace setBaseUrl of course)

Problem was in assets(js files).
Need to do rake assets:precompile before deploy on heroku or include rake/assets/* in gitignore.

Related

Angular with Rails API: "Failed to load resource: the server responded with a status of 401 (Unauthorized)"

So I am deploying an Angular 5 app with a Rails 5 back-end. I can get the data to flow properly between the two locally, but trying to connect to the deployed version of the API (which is on Heroku) I run into some authorization issue. The error is:
Failed to load https://my_api.herokuapp.com/data.json: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:4200' is therefore not allowed access.
The response had HTTP status code 404.
Cross-Origin Read Blocking (CORB) blocked cross-origin response <URL> with MIME type application/json.
See <URL> for more details.
Is this something I need to change within the Rails API or in Angular? The deployed Rails API is essentially the same as the local version so I'm not sure where the disconnect is coming from.
There are only two refrences to the API in Angular. I connect to it the same way that I do to the local server:
Angular, app-module.ts
providers: [Angular2TokenService, AuthService, AuthGuard,
// {provide: 'api', useValue: 'http://localhost:3000/'}
{provide: 'api', useValue: 'https://my_ api.herokuapp.com/data.json'}
]
Perhaps it's my use of Angular2TokenService?
Angular, environment.ts:
export const environment = {
production: false,
token_auth_config: {
// apiBase: 'http://localhost:3000'
apiBase: 'https://my_api.herokuapp.com/data.json'
}};
Thanks! Let me know of any suggestions you might have or if you need clarification.
It's issue with CORS(cross-origin-resource-sharing). You can handle it by adding callback in your API like below:
def cors_set_access_control_headers
headers['Access-Control-Allow-Origin'] = ENV['SERVER_URL'] || '*'
end
where SERVER_URL is your front-end server URL
Else you can use gem 'rack-cors' as suggested in comments by #Kedarnag Mukanahallipatna

Javascript reading server file GET http://localhost:3000/public/uploads/goodj.json 404 (Not Found)

I am trying to read server file in javascript in ruby on rails project.
$.ajax({
url: "/public/uploads/goodj.json",
success: function (file_content) {
console.log(file_content);
}
});
And this causes error
GET http://localhost:3000/public/uploads/goodj.json 404 (Not Found)
I think server is recognizing this request as action of controller.
What can I do to make server to understand this is request for reading file?
From Rails guides:
config.public_file_server.enabled configures Rails to serve static
files from the public directory. This option defaults to true, but in
the production environment it is set to false because the server
software (e.g. NGINX or Apache) used to run the application should
serve static files instead. If you are running or testing your app in
production mode using WEBrick (it is not recommended to use WEBrick in
production) set the option to true. Otherwise, you won't be able to
use page caching and request for files that exist under the public
directory.
And the URL should be /uploads/goodj.json, not /public/uploads/goodj.json. So the code snippet should look like that:
$.ajax({
url: "/uploads/goodj.json",
success: function (file_content) {
console.log(file_content);
}
});

angular2 & lite server dot in url leads to 404 not found

I'm using Angular2 Beta 14 and calling a URL with a "dot" in it leads to a 404 not found error from the lite server which is 2.2.0.
This is the URL I'm calling:
http://localhost:3000/confirmuser/token/eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjYsInVzZXJOYW1lIjoiYXNkZmFzQGNlZC5saSJ9.PMzNWp8mbUKbSAiOqhOqjhZUYNejXY3pIQueBkc8_2E
The router path in app.component.ts looks like this:
{path: '/confirmuser/token/:token', name: 'ConfirmUser', component: ConfirmUserComponent}
The Chrome console shows this:
Failed to load resource: the server responded with a status of 404 (Not Found)
Ant the Lite Server:
[1] 16.04.13 15:57:13 404 GET /confirmuser/token/eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjYsInVzZXJOYW1lIjoiYXNkZmFzQGNlZC5saSJ9.PMzNWp8mbUKbSAiOqhOqjhZUYNejXY3pIQueBkc8_2E
When ever I call the url without a "dot", the page gets loaded correctly.
My aim here is, to confirm a user sign up. He receives an email with an URL he has to confirm. Using a JWT in this (and other cases) is habit I've been using.
Now I doubt this is an Angular issue, I believe this is a lite server issue.
Anyone experience with this?
Thanks
I found a suitable workaround for this issue.
Basically I'm getting rid of the path parameter ":token" and replacing it by a query parameter
In the app.component.ts the new path now looks like this:
{path: '/confirmuser', name: 'ConfirmUser', component: ConfirmUserComponent}
An the URL like this:
http://localhost:3000/confirmuser?token=eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjYsInVzZXJOYW1lIjoiYXNkZmFzQGNlZC5saSJ9.PMzNWp8mbUKbSAiOqhOqjhZUYNejXY3pIQueBkc8_2E
In the component that handles this request I can continue to call route params as I was used to. So nothing to change there:
constructor(params: RouteParams){
this.token = params.get('token')
...
This question has been answered in https://stackoverflow.com/a/36283859/1465640#
But it can be summarized with dots doesn't work in urls unless you do some work on the lite-server config.
If you are using webpack then you need to change the config to make it working.
Please make the change in webpack dev server config file
historyApiFallback: {
disableDotRule: true
},

XMLHttpRequest cannot load file?

d3.csv("result.csv", function(flights) {
var nestByDate = d3.nest()
.key(function(d) { return d3.time.day(d.date); });
..........
When I am trying to run above d3.js code from web server then it executes d3.js properly by loading csv file.
but when I am trying to run d3.js as shown below,
d3.csv("D:\\Project Space\\D3Demo\\WebContent\\result.csv", function(flights) {
var nestByDate = d3.nest()
.key(function(d) { return d3.time.day(d.date); });
..........
then it shows following error:
XMLHttpRequest cannot load file:///D:/Project%20Space/D3Demo/WebContent/result.csv. Cross origin requests are only supported for HTTP`
How to solve this problem ?
There is no way to solve the problem using D3's convenience functions.
d3.csv fundamentally is an AJAX request and is beholden to the same-origin policy.
When you load the file location, your browser realizes that the requested file does not exist on the same domain (likely localhost in your case) and prevents the request from completing.
A simple way to get around this would be to simply serve the content over localhost or whatever you are using.
Alternatively you can look in to Cross-origin Resource Sharing, or for better compatibility: JSONP. In both of these cases you will likely have to roll your own function to convert the CSV data into a javascript array.

Jquery's ajax request fails in remote, not in local

I am using an ajax request which works in local, not in remote, because of an url problem. It looks like :
$.ajax({
type: "POST",
url: "../classes/file_to_process.php",
data: "my data"
success: function(msg){...}
})
I keep on having an error message : "The requested URL /classes/file_to_process.php {without the double dots behind it} was not found on this server"
My working directory is in a folder /prod, in which there is the index.php. The /classes folder is at the same level as /prod. So to fetch it from an jquery request, I use ../classes/file_to_process
I tried an absolute path by using pwd to fetch the correct path on the remote server, but I have the same message
Anybody has an idea ?
'classes' folder is on the same level as 'public', then you can't access it directly from the client (AJAX, JavaScript, etc). You need to either put it in the 'public' or map it to /classes virtual path. Or you can have a trusted .php file in your 'public' folder that accesses the 'classes' on the server side.
TL;DR;
From the client side you cannot access a file that is not being served to the client.

Resources