I want to add these libs to my app.
<script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-app.js" crossorigin="anonymous"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-database.js" crossorigin="anonymous"></script>
The server is run on localhost.
But the console says it cannot access the script to CORS policy. I searched and tried all solutions but nothing worked. Please help.
The server doesn't allow CORS access to those scripts, so either stop asking for CORS access (remove the crossorigin attribute) or reconfigure the server to grant permission with a Access-Control-Allow-Origin response header.
Related
I'm new to web development, javascript, and node js.
I know that there are a lot of questions on the cors error already I have spent 2 days looking at solutions to my problem but I can't figure out how to solve this cors error.
yesterday after 2 days of searching I finally found a solution that worked at first but now it only works 20% of the time and the other 80% I get another error.
I set up my socket.io and tried to send sockets through socket.io exactly as shown in this youtube video:
https://www.youtube.com/watch?v=rxzOqP9YwmM&t=5s
Although my code was exactly the same as in the video I kept getting a cors error when sending sockets.
Here is some of my server-side code:
const io = require("socket.io")(3000);
var fs = require('fs');
io.on("connection", socket => {...
Here is some of my client side code:
const socket = io("http://localhost:3000");
socket.on("new_partner", recieved_data => {
partner_user.username = recieved_data;
socket.emit("logged_in", this_user.username);
});
...
Here is the head of my html:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<meta charset="utf-8">
<title>real time chat</title>
<link rel="stylesheet" href="chat_room.css">
<script defer src="http://localhost:3000/socket.io/socket.io.js"></script>
<script defer src="script.js"></script>
<script defer src="login.js"></script>
</head>
Here is the cors error I kept getting with the above code:
Access to XMLHttpRequest at 'http://localhost:3000/socket.io/?EIO=4&transport=polling&t=NP9ZPIk' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
After A LOT of searching I changed my server-side code to this:
const io = require("socket.io")(3000, { cors: { origin: "*", }, });
var fs = require('fs');
io.on("connection", socket => {
The first time I ran the new code everything worked PERFECTLY. After some additional testing, I soon realized this method only works 20-30% of the time. The other 70% of the time I kept getting some other random errors. today when I tried to reproduce the errors to be able to ask on StackOverflow (here) for some help, I wasn't getting the same error as yesterday anymore. I don't know what exactly is going on since I'm a huge beginner to web development but here are the errors I keep getting today when I try to send sockets to my server from my client:
GET http://localhost:3000/socket.io/socket.io.js net::ERR_CONNECTION_REFUSED
Uncaught ReferenceError: io is not defined
at script.js:1
Uncaught ReferenceError: socket is not defined
at login.js:1
I should also mention that with this new method unlike with the cors error I can get my site to load but once I try sending sockets that's when the error pops up in the console.
I know this is probably basic and that one of these days I really need to sit down and thoroughly look at the socket io documentation, but I really don't have the time with this project's deadline right now.
Again I apologize for my ignorance and thanks in advance.
Here is all of my code if it helps:
html(index.html): https://pastebin.com/RQ7zNzdy
client-side script(script.js): https://pastebin.com/1P0DJ6HH
client side login(script.js): https://pastebin.com/fqtNRQvg
server side script(server.js): https://pastebin.com/NTL6ynup
css of my website(not that it matters): https://pastebin.com/24rF8urG
Here is the post that might help.
To verify if that is the problem try running client from e.g. Firefox.
I have an Angular app running in gh-pages https://yourweatherapp.github.io/yourweatherapp.github.io which make requests to a node.js app that it´s running in a host.
Previously, I have consulted other info on the net like this How to allow CORS?, but solutions don´t work for me
I have configured the node.js app to allow request from this origin on this way:
const corsMiddleware = cors({
origin: [process.env.URL, 'https://yourweatherapp.github.io/yourweatherapp.github.io/login']
})
app.use(corsMiddleware)
app.options('*', corsMiddleware)
But the browser doesn´t allow to receive the answer and do login.
What am I doing wrong?
'https://yourweatherapp.github.io/yourweatherapp.github.io/login'
Look at the error message in the browser console. It will tell you the origin that doesn't have permission to read the data, and it won't be that.
Origins do not include paths. So that is not a valid origin.
It should be only https://yourweatherapp.github.io
We have deployed the api on azure and trying to consume in our web app written in angular 5. However when we try to consume the api we are getting following errors.
Chrome Mixed Content: The page at 'https://somedevapp.azurewebsites.net/#/managesomething' was loaded
over HTTPS, but requested an insecure XMLHttpRequest endpoint
'http://admindevapp.azurewebsites.net/api/data/getdata'. This request
has been blocked; the content must be served over HTTPS.
Firefox Blocked loading mixed active content
Is this issue related to CORS? How to resolve this issue?
Any help on this appreciated!
If your web app is being hosted over HTTPs as you've indicated, then all external resources it is consuming (CDN, scripts, CSS files, API calls) should also use SSL and be secured through HTTPs. Think about it. It would defeat the purpose of your app being secure, if your app was in turn making insecure requests to an API.
You can either therefore:
As Chrome suggests, change your API calls to use HTTPs (recommended)
Use HTTP instead of HTTPs
Add the following meta tag to your <head> element in your HTML:
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests" />
More information about this can be found here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/upgrade-insecure-requests.
Use this ---- Add in your head section
I will try this with my weather application & now it's working fine
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
only add this on header section.
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
you can use this only if your resource API supports the HTTPS request.
example: "http://ip-api.com/json" and "https://ip-api.com/json" both will not return the same response if "ip-api.com" doesn't support HTTPS requests.
The meta tag below helps to prevent Chrome complaining about HTTP request made. I was working on a class projects (a weather app) and the API call over HTTP and adding an S to the HTTP call doesn't help. Since this a project a there no major issue. The meta tag share above by #Medhi Ibrahim does the trick.
<meta
http-equiv="Content-Security-Policy"
content="upgrade-insecure-requests"
/>
i tried to remove the "meta solution" on index.
And removed the "s" on environment.prod.ts
When i sign in " http://app.finoview.com" the api Nestjs works.
But when i try to log in "https://finoview.com", angular works, but the api nestjs doesnt work.
Here is the image:
I am requesting an image from Cloudfront CDN. each time I make a request from the client I am getting this error:
Access to Image at https://cdn.mywebsite/image.png from origin
http://localhost:5000 has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin http://localhost:5000 is therefore not allowed
access. The response had HTTP status code 403.
I'm using express for the server and have added the following to allow Access but still no luck..
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', "*");
res.setHeader('Access-Control-Allow-Methods', 'GET');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
next();
})
Any Advice would be much appreciated!
==========================================================================
Update
Hi #jfriend00
So what my goal is to serve protected content over CF CDN.
For this I am sending signed Cookies to the client using the following module below.
var cf = require('aws-cloudfront-sign')
var options = {keypairId: 'keypairId', privateKeyPath: '/foo/bar'}
var signedCookies = cf.getSignedCookies('https://cdn.mywebsite.com/*', options);
for(var cookieId in signedCookies) {
res.cookie(cookieId, signedCookies[cookieId]);
}
Then I am simply making a request from the client to the cdn to fetch the image with:
<img src="https://cdn.mywebsite.com/image.png" crossorigin="anonymous" alt="test picture">
At this point the Access-Control-Allow-Origin error is displayed in the console.
Note:
var signedUrl = cf.getSignedUrl('https://cdn.mywebsite.com/image.png', options)
This signedUrl works when directly accessing it but not if I make the request from localhost or the website it self.
CORS headers have to be on the server that is serving the resource. So, if the resource that you are getting the CORS error on is https://cdn.mywebsite/image.png, then that's the host that has to allows CORS access. You can't fix that by allowing CORS on localhost.
FYI, it seems odd that you are getting a CORS error when accessing an image. If you use <img> tag for the access, then the <img> tag will not be subject to same origin restrictions. The same origin restrictions apply to Ajax calls made from browser Javascript.
I also not that you appear to be mixing http and https in the same page which can also cause issues.
Are you trying to download the image with Ajax? Please show your client code that is causing this error and explain what you are trying to accomplish and perhaps we can offer a different solution.
For a few days we'r trying to integrate drupal with node.js. but we couldn't connect with socket.io.js..
we're getting this error message from chrome console;
XMLHttpRequest cannot load http://mydomainname.com:8080/socket.io/1/?t=1340201859161. Origin http://mydomainname.com is not allowed by Access-Control-Allow-Origin.
and our backend settings are;
/**
* This configuration file was built using the 'Node.js server configuration builder'.
* For a more fully commented example see the file nodejs.config.js.example in the root of this module
*/
backendSettings = {
"scheme":"http",
"host":"mydomainname",
"port":8080,
"key":"/path/to/key/file",
"cert":"/path/to/cert/file",
"resource":"/sites/all/modules/nodejs/node_modules/socket.io/lib",
"publishUrl":"publish",
"serviceKey":"",
"backend":{
"port":80,
"host":"urb5.com",
"messagePath":"realtime"},
"clientsCanWriteToChannels":false,
"clientsCanWriteToClients":false,
"extensions":["nodejs.server.extension.js"],
"debug":true,
"transports":["websocket",
"flashsocket",
"htmlfile",
"xhr-polling",
"jsonp-polling"],
"jsMinification":true,
"jsEtag":true,
"logLevel":1};
and also, in source code we have a script socket.io script,
like
<script type="text/javascript" src="http://mydomainname.com:8080/sites/all/modules/nodejs/node_modules/socket.io/lib/socket.io.js"></script>
this scripts build number is 0.9.6, but if we follow this path in ftp, there is a socket.io.js but its build number is 0.9.5
any suggestions?,
thanks..
The problem here, is that you are trying to load up socket.io from the server, but your front-end files are located in another domain space / server.
There is security regulations that does not allows cross-domain ajax and resources requests if they are not enabled by server.
So on server side where socket.io.js is coming from, you should add in page header something like this:
Access-Control-Allow-Origin: http://hello-world.example
Access-Control-Max-Age: 3628800
Access-Control-Allow-Methods: PUT, DELETE
This will allow you to share resource content with specified domain. And browser will not throw Access-Control-Allow-Origin error anymore.
As well, why you are trying to include js file through port 8080? If this is port that you bind your socket.io listener, then this is wrong, and you need to get js file through usual port (in most cases without defining, or 80).