'XMLHttpRequest cannot load' Error on HTTP Requests from Dart client to local Dart docker server - xmlhttprequest

I've lately been trying to build a Dart client that communicates with my Dart docker server. If I run this url (localhost:8080/id/6192449487634432) on any browser I get back a JSON that I've set up, however, if a use
HttpRequest
.getString ("http://localhost:8080/id/6192449487634432")
.then (print);
on the Dart client, I get this weird error
XMLHttpRequest cannot load http://localhost:8080/id/6192449487634432. No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin 'http://localhost:8081' is therefore not allowed access.
I've searched and some workarounds have been to build a PHP proxy (no thanks). I am new to web development in general and I definitely don't know what a proxy is or how to build one. Is there a clean solution I could use? I have a Redstone server and and AngularDart client.

This happens when your client app is served from a different server than your docker server. This is a browser issue, not specific to Dart. Luckily, the solution is easy.
Be sure to send CORS headers from your server, on every request. The easiest way to solve this is to add the following header:
Access-Control-Allow-Origin: *
I don't know the specifics of Redstone, but be sure to set the header key Access-Control-Allow-Origin and value * on GET, HEAD, and POST methods. Yes, you need to set this header on HEAD requests because sometimes the browser does a HEAD request to check if CORS is enabled.
Learn more about CORS at http://enable-cors.org/

As mentioned above setting the Access-Control-Allow-Origin header allows HTTP requests from the browser to go to other URLs than the origin the client was loaded from. Another option is to serve the Dart client from the same server as you are accessing.
Depending on your environment and whether you are using Dartium or a JavaScript browser
If you are using Dart on App Engine Managed VMs we have built-in support for this, so that requests for the client files are proxied to pub serve during development and served from the output from pub build when deployed. See A Client-Server Example.
If you are running a plain Dart server right now there is no canned solution for switching between pub serve and pub build. You can run pub build and serve the files out of the web/build directory.
We are working on making the solution provided for Dart on App Engine Managed VMs more generally available.

Particularly to redstone, you can solve the problem as follows. Add to your server-side code this snippet
// if not yet there
import 'package:redstone/server.dart' as app;
#app.Interceptor(r'/.*')
interceptor() {
app.chain.next(() {
app.response = app.response.change(headers: {
"Access-Control-Allow-Origin": "*"
});
});
}
you can read more on interceptors in the redstone wiki

Related

I want to add the ID in the API [duplicate]

I am working on an app using Vue js.
According to my setting I need to pass to a variable to my URL when setting change.
<!-- language: lang-js -->
$.get('http://172.16.1.157:8002/firstcolumn/' + c1v + '/' + c1b, function (data) {
// some code...
});
But when my app hit on URL, it shows the following message.
Failed to load http://172.16.1.157:8002/firstcolumn/2017-03-01/2017-10-26: Redirect from 'http://172.16.1.157:8002/firstcolumn/2017-03-01/2017-10-26' to 'http://172.16.1.157:8002/firstcolumn/2017-03-01/2017-10-26/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
In addition to what awd mentioned about getting the person responsible for the server to reconfigure (an impractical solution for local development) I use a change-origin chrome plugin like this:
Moesif Orign & CORS Changer (use to be free but now wants a work email address >_>)
Allow CORS: Access-Control-Allow-Origin
You can make your local dev server (ex: localhost:8080) to appear to be coming from 172.16.1.157:8002 or any other domain.
In case the 2nd plugin link breaks in the future or the plugin writer decides to capitalize off the fame of this thread, open your browser's
plugin marketplace and search "allow cors", there's going to be a
bunch of them.
Thanks all, I solved by this extension on chrome.
Allow CORS: Access-Control-Allow-Origin
If you have control over your server, you can use PHP:
<?PHP
header('Access-Control-Allow-Origin: *');
?>
Ask the person maintaining the server at http://172.16.1.157:8002/ to add your hostname to Access-Control-Allow-Origin hosts, the server should return a header similar to the following with the response-
Access-Control-Allow-Origin: yourhostname:port
Using npm:
To allow cross-origin requests install 'cors':
npm i cors
Add this in the server-side:
let cors = require("cors");
app.use(cors());
When you have this problem with Chrome, you don't need an Extension.
Start Chrome from the Console:
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
Maybe you have to close all Tabs in Chrome and restart it.
I will assume that you're a front-end developer only and that you don't have access to the backend of the application (regarding the tags of the question).
Short answer on how to properly solve this in your case? You can't, you'll need somebody else.
What is this about?
You need to understand that CORS is a security thing, it's not just here to annoy you just for fun.
It's purpose is to mainly prevent the usage of a (malicious) HTTP call from a non-whitelisted frontend to your backend with some critical mutation.
You could give a look to this YouTube video or any other one really, but I recommend a visual video because text-based explanation can be quite hard to understand.
You also need to understand that if you use Postman or any other tool to try your API call, you will not get the CORS issue. The reason being that those tools are not Web frontends but rather some server-based tools.
Hence, don't be surprised if something is working there but not in your Vue app, the context is different.
Now, how to solve this?
Depending of the framework used by your backend team, the syntax may be quite different but overall, you'll need to tell them to provide something like Access-Control-Allow-Origin: http://localhost:3000 (or any other port you'll be using).
PS: Using Access-Control-Allow-Origin: * would be quite risky because it would allow anybody to access it, hence why a stricter rule is recommended.
If you're using a service, like an API to send SMS, payment, some Google console or something else really, you'll need to allow your localhost in the dashboard of the service. Ask for credentials to your manager or Tech Lead.
If you have access to the backend, you could it yourself as shown here (ExpressJS in this example): https://flaviocopes.com/cors/
How to hack it in a dirty way?
If you're in a damn hurry and want to get something really dirty, you could use a lot of various hacks a listed in the other answers, here's a quick list:
use any extension who is able to create a middleware and forward the request to the backend (it will work because it's not directly coming from your frontend)
force your browser to disable CORS, not sure how this would actually solve the issue
use a proxy, if you're using Nuxt2, #nuxtjs/proxy is a popular one but any kind of proxy (even a real backend will do the job)
any other hack related somehow to the 3 listed above...
At the end, solving the CORS issue can be done quite fast and easily. You only need to communicate with your team or find something on your side (if you have access to the backend/admin dashboard of some service).
I heavily do recommend trying get it right from the beginning because it's related to security and that it may be forgotten down the road...
The approved answer to this question is not valid.
You need to set headers on your server-side code
app.use((req,res,next)=>{
res.setHeader('Access-Control-Allow-Origin','*');
res.setHeader('Access-Control-Allow-Methods','GET,POST,PUT,PATCH,DELETE');
res.setHeader('Access-Control-Allow-Methods','Content-Type','Authorization');
next();
})
You can also try a chrome extension to add these headers automatically.
Hello If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.
When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:
Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.
To add the CORS authorization to the header using Apache, simply add the following line inside either the <Directory>, <Location>, <Files> or <VirtualHost> sections of your server config (usually located in a *.conf file, such as httpd.conf or apache.conf), or within a .htaccess file:
Header set Access-Control-Allow-Origin "*"
And then restart apache.
Altering headers requires the use of mod_headers. Mod_headers is enabled by default in Apache, however, you may want to ensure it's enabled.
I had the same problem in my Vue.js and SpringBoot projects. If somebody work with spring you can add this code:
#Bean
public FilterRegistrationBean simpleCorsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
// *** URL below needs to match the Vue client URL and port ***
config.setAllowedOrigins(Collections.singletonList("http://localhost:8080"));
config.setAllowedMethods(Collections.singletonList("*"));
config.setAllowedHeaders(Collections.singletonList("*"));
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean<>(new CorsFilter(source));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
I found solution in this article Build a Simple CRUD App with Spring Boot and Vue.js
You are making a request to external domain 172.16.1.157:8002/ from your local development server that is why it is giving cross origin exception.
Either you have to allow headers Access-Control-Allow-Origin:* in both frontend and backend or alternatively use this extension cors header toggle - chrome extension unless you host backend and frontend on the same domain.
Try running this command in your terminal and then test it again.
curl -H "origin: originHost" -v "RequestedResource"
Eg:
If my originHost equals https://localhost:8081/ and my RequestedResource equals https://example.com/
My command would be as below:
curl -H "origin: https://localhost:8081/" -v "https://example.com/"
If you can notice the following line then it should work for you.
< access-control-allow-origin: *
Hope this helps.
Do specify #CrossOrigin(origins = "http://localhost:8081")
in Controller class.
You can solve this temporarily by using the Firefox add-on, CORS Everywhere. Just open Firefox, press Ctrl+Shift+A , search the add-on and add it!
You won't believe this,
Make sure to add "." at the end of the "url"
I got a similar error with this code:
fetch(https://itunes.apple.com/search?term=jack+johnson)
.then( response => {
return response.json();
})
.then(data => {
console.log(data.results);
}).catch(error => console.log('Request failed:', error))
The error I got:
Access to fetch at 'https://itunes.apple.com/search?term=jack+johnson'
from origin 'http://127.0.0.1:5500' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
But I realized after a lot of research that the problem was that I did not copy the
right URL address from the iTunes API documentation.
It should have been
https://itunes.apple.com/search?term=jack+johnson.
not
https://itunes.apple.com/search?term=jack+johnson
Notice the dot at the end
There is a huge explanation about why the dot is important quoting issues about DNS and character encoding but the truth is you probably do not care. Try adding the dot it might work for you too.
When I added the "." everything worked like a charm.
I hope it works for you too.
install:
npm i cors
Then include cors():
app.get("/list",cors(),(req,res) =>{
});
In addition to the Berke Kaan Cetinkaya's answer.
If you have control over your server, you can do the following in ExpressJs:
app.use(function(req, res, next) {
// update to match the domain you will make the request from
res.header("Access-Control-Allow-Origin", "YOUR-DOMAIN.TLD");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
https://enable-cors.org/server_expressjs.html
I tried this code,and that works for me.You can see the documentation in this link
var io = require("socket.io")(http, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
})
The reason that I came across this error was that I hadn't updated the path for different environments.
you have to customize security for your browser or allow permission through customizing security. (it is impractical for your local testing)
to know more about please go through the link.
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
These errors may be caused due to follow reasons, ensure the following steps are followed. To connect the local host with the local virtual machine(host). Here, I'am connecting http://localhost:3001/ to the http://abc.test Steps to be followed:
1.We have to allow CORS, placing Access-Control-Allow-Origin: in header of request
may not work. Install a google extension which enables a CORS request.*
2.Make sure the credentials you provide in the request are valid.
3.Make sure the vagrant has been provisioned. Try vagrant up --provision this make the localhost connect to db of the homestead.
Try changing the content type of the header. header:{ 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8;application/json' }
this point is very important.
Another solution to this problem in a specific scenario :
If
AWS APIGW is your backend with authentication enabled and
authentication fails,
your browser may end up complaining about CORS even if CORS is enabled in APIGW. You also need to enable CORS for 4XX as follows
API:YourAPI > Resources > /YourResource > Actions > Enable CORS > Gateway Responses for yourAPI check Default 4XX
Authentication will still fail but it won't look like CORS is the root cause
$.get('https://172.16.1.157:8002/firstcolumn/' + c1v + '/' + c1b, function (data) {
// some code...
});
Just put "https" .

frontend cloud run app can not access my backend cloud run app due a MixedContent problem

I have two cloud services up and running.
frontend (URL: https://frontend-abc-ez.a.run.app/)
backend (URL: http://backend-abc-ez.a.run.app/)
Frontend is calling the backend through a nuxt.js server middleware proxy to dodge the CORS problematics.
The call is coming through - I can see that in the backend log files. However the response is not really coming back through because of CORS. I see this error in the console:
Mixed Content: The page at 'https://frontend-abc-ez.a.run.app/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://backend-abc-ez.a.run.app/login'. This request has been blocked; the content must be served over HTTPS.
What I find weird is that I configured the backend url with https but it is enforced as http - at least that is what the error is telling me. Also I see a /login path segment in the unsecure URL. Why is that? I never explicitly defined that endpoint. Is it the security layer proxy of the run service itself?
Anyway - I need to get through this properly and am having a hard time to understand the source of the problem.
For some reason as I rechecked the applications today in the morning everything went fine. I have really no idea why it is working now. I did not change a thing - I waited for the answers here before I'd continue.
Very weird. But the solution so far seems to be waiting. Maybe Cloud Run had some troubles.

How to fix "Cross-Origin Read Blocking (CORB) blocked cross-origin response with MIME type application/json." issue?

I'm currently developing the frontend (VueJS) for a project and to test my login and register logics I'm using laravel as backend, though we'll be actually working with springboot for backend. I was coding in a desktop and everything was normal. So I just started to work with my laptop. I got the same project, everything is equal. When I use postman to make the requests, it works normally, but when I try to make them with the form from my website, I get that error.
I've looked everywhere but couldn't fix it. Nothing I tryed did work. And It seems that no one else had a similar problem.
Cross-Origin Read Blocking (CORB) blocked cross-origin response http://127.0.0.1:8000/api/login with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.
Add proxy configuration in vue.config.js file
module.exports = {
devServer: {
proxy: 'http://localhost:4000'
}
}
This will tell the dev server to proxy any unknown requests (requests that did not match a static file) to http://localhost:4000.
here is a link to the doc for more detail

Angular2 - How can I add HTTP headers to responses my app sends to the browser?

I'm prototyping an Angular2 app at work. The app should run under some company middleware that expects several Link headers in responses it gets from the angular2 app. Unfortunately, I haven't been able to figure out how to add headers to responses that Angular provides out of the box.
To clarify what I mean - when I send a GET Request directly to my Angular app, it sends back a Text/HTML response that a browser can render into an SPA. I would like to add headers to this response, and can't figure out how. The closest I've found is the discussion here: Angular2 - set headers for every request
This sounds like a duplicate, but having looked through similar questions, I've found how to add headers to Responses I generate explicitly with an HTTP object from the HttpModule, but not how to attach headers to the Responses that Angular creates out-of-the-box. I'd love to use something like an HTTP Interceptor that just attaches headers to every response my app sends out, but it doesn't look like Angular2 will have interceptors until release 4.1.
Edit: Things I've tried:
Adding a provider for Http ResponseOptions in my (main) AppModule that adds headers to responses
This adds the header to all responses I receive from http requests that my app receives from the HttpModule, but doesn't add the header to responses that my app itself sends to outside services.
Edit 2: I misunderstood where my Angular app ends and where the server hosting it begins. Headers like this can be added in the server - for my simple example, I needed to configure the webpack-dev-server. See the accepted answer below.
Web Starter Pack uses webpack-dev-server just as a development hosting platform/Web server for your efforts, but it 's not, in the end, part of your final Angular app proper. You'll eventually serve your Angular app from some other hardened Web server software such as Apache, IIS, etc.
For development purposes, you should be able to configure webpack-dev-server to add custom headers by modifying your webpack.config.js by setting the headers options, per the documentation.
devServer.headers
Adds headers to all requests:
headers: {
"X-Custom-Foo": "bar"
}
For example:
webpack.config.js
...
devServer: {
...
headers: {
"X-Custom-Foo": "bar"
}
...
}
...
Although to actually read the "initial load" headers within your Angular application once it initializes (if that is what you're looking to do) you may need to add your values as [non-httpOnly] cookies, then read them on ngInit().
Source: DevServer Documentation - Header
I don't know the angular2-webpack-starter, but I guess it's just a command line tool easy development of your Angular application. So it just serves your JavaScript, HTML and assets. It's not the application itself. The Angular application runs in a browser and serves as a client of your backend. So you need another server that serves your backend application and all your XHR calls will go to this backend. When you deploy your application, it will probably not run in the angular2-webpack-starter, but in some more advanced HTTP server such as Apache HTTPD or nginx.
Then you need to create a custom Http service (extending angular's own Http service) or XHRBackend. It has access to Request and Response object and can add extra headers there.

Different ports for frontend and backend. How to make a request?

Using Angular-CLI as a frontend. 4200 port
Using Express as a backend. 8080 port
Directories look like:
Application
- backend
- ...Express architecture
- frontend
-...Angular2 architecture
So I'm running two projects, two commanders, one for frontent, second one for backend. node app.js for backend (8080), ng serve for frontent (4200).
Let's assume that I have a layer in backend which returns some string.
app.get('/hello', function(req, res) {
res.send("Hello!");
}
How can I make a request from frontend to backend and get that string? I don't want to know how exactly should I use Angular2 because that's not the point. I'm asking, what technology should I use to be able connect these two (frontent and backend) sides on different ports. If I just run them and make a request from frontend, I'll get an error because it can't find /hello url.
Your request to /hello means an absolute path inside the application running the angular application, so the request goes to http://localhost:4200/hello. Your angular application just doesn't know about the express application you want to target.
absolute urls
If you want to access the hello route on the other (express) application, you need to explicitly specify this by referencing http://localhost:8080/hello.
cors
Doing it this way, the correct application is targeted, but you will likely run into CORS issues, because the browser will prevent the javascript code obtained from localhost:4200 to access a server at localhost:8080. This is a security feature of your browser. So if you want to allow the code at 4200 to access the backend at 8080 your backend can whitelist this so called origin. For details see http://enable-cors.org/ and a corresponding express middleware you could use to support cors in your backend (https://www.npmjs.com/package/cors).
Using this approach has two downsides in my opinion. First, you need a way to tell your frontend under which absolute url it can reach the backend. This must be configurable because you need different urls for dev, staging and production. You then also need a way to manage all your whitelisted urls because the frontend in production will have a different url than when running the frontend in development. This can get pretty cumbersome to handle.
proxying your backend
A better approach in my opinion is to handle this in your infrastructure by proxying the backend in your frontend application. With proxying you basically tell your frontend server that all requests to some url should be passed through to another application. In your case this could probably mean, that for example you configure a proxy for the path /api/ to proxy the application on localhost:8080. The server then doesn't try to find a url like /api/hello on your frontend application but forwards your request to localhost:8080/hello. In your angular application you then don't need to care about the url of your backend and you can then always do a request to a url like /api/some-express-route.
For this to work you need to configure your angular dev server to proxy the requests. For details on how to do this, please see the docs at https://angular.io/guide/build#proxying-to-a-backend-server. When going to production, you can do this by configuring your web server, e.g. nginx to proxy the requests.