I have an error on a web application developed with VueJs that uses Axios.
Access to XMLHttpRequest at `URL API` from origin `URL APP` has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Example of a request :
axios
.get(
store.getters.getURL +
"/TennisStats?MatchId=" +
this.$route.params.id +
"&season=" +
season,
{ }
)
.then(function (response) {
I have a devServer set up:
module.exports = {
devServer: {
proxy: 'https:/URL_APP/api/',
},
The application is hosted on AWS.
The error appears randomly and when the cache is deleted, it disappears again for a while.
I don't know what to do... can you reproduce the error and guide me in my search for the cause?
Can you try going incognito and trying? Might be a caching issue since you are working on the same machine. Also if this does not work try restarting the AWS server, or try running the hosted application on a different machine.
Related
I have built a real estate site that makes a an api request to "https://completecriminalchecks.com" In development mode I was getting the dreaded blocked by Cors error. Through some research I found that I needed to use a proxy to solve the issue, which it did in development mode on my local host. But now I have deployed the site to netlify, I am getting a 404 error when making the request. when I look at the request from the network devtools its says
Request URL: https://master--jessehaven.netlify.app/api/json/?apikey=6s4xxxxx13xlvtphrnuge19&search=radius&miles=2¢er=98144
I dont think this is right. How do i make netlify make the proper request to the api that was having cors issues in development?
Have you tried netify documentation about it?
Proxy to another service Just like you can rewrite paths like /* to
/index.html, you can also set up rules to let parts of your site proxy
to external services. Let's say you need to communicate from a
single-page app with an API on https://api.example.com that doesn't
support CORS requests. The following rule will let you use /api/ from
your JavaScript client:
/api/* https://api.example.com/:splat 200
Now all requests to /api/... will be proxied through to
https://api.example.com straight from our CDN servers without an
additional connection from the browser. If the API supports standard
HTTP caching mechanisms like ETags or Last-Modified headers, the
responses will even get cached by our CDN nodes.
You do not need to use a proxy, you enable CORRS in your server. Are you using a onde server?
If you use express something like this:
npm install --save cors
And then use it as middleware:
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
Also in your netlify.toml file this will do the trick:
# The following redirect is intended for use with most SPAs that handle
# routing internally.
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
[[headers]]
# Define which paths this specific [[headers]] block will cover.
for = "/*"
[headers.values]
Access-Control-Allow-Origin = "*"
I also faced the same issue and solved by creating a netlify.toml file in root directory.
Here is a sample code for redirect which worked for me.
Place this inside the netlify.toml file.
Documentation guide for proxy :
[[redirects]]
from = "/api/users/tickets/"
to = "https://some-external-site.com/api/users/tickets/"
status = 200
force = true
headers = {Access-Control-Allow-Origin = "*"}
[[redirects]]
from = "/api/users/cars/*"
to = "https://some-external-site.com/api/users/cars/:splat"
status = 200
force = true
headers = {Access-Control-Allow-Origin = "*"}
I also faced the same issue , so I removed the "proxy" from the "package.json" file and created a variable to store the IP addess or URL for backend , then used it with the URL parameter for calling API. The CORS issue is solved in backend by allowing "All origins".
File to store base URL:
constant.js :
export const baseUrl = "https://backEndUrl";
File to call API:
getDataApi.js:
import { baseUrl } from "./constant";
export const getProfileData = () => (dispatch) => {
axios
.get(`${baseUrl }/api/profile`)
.then((res) =>
dispatch({
type: GET_PROFILE,
payload: res.data,
})
)
.catch((err) =>
dispatch({
type: GET_PROFILE,
payload: null,
})
);
};
Package: apollo-server-express
Version: v2.6.0
Issue: CORS settings aren't taking effect.
Reported to Apollo?: Yes, Issue 3058
Description: From our react client, we started sending apollographql-client-name & apollographql-client-version headers for better client awareness in Apollo Engine.
Access to fetch at 'https://something.com/graphql' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field apollographql-client-name is not allowed by Access-Control-Allow-Headers in preflight response.
We receive above CORS error. We enabled cors on Apollo Server through express middleware by passing cors: true. For some reason, this changes are not making any difference. We continue to receive above error.
const server: ApolloServer = new ApolloServer({
...
...
});
const app: Application = express();
server.applyMiddleware({
app,
cors: true,
path: '/graphql',
});
We have nginx sitting in front and it does receive request and forwards to Apollo Server.
cors: true enables everything by default?
We tried being very specific but that didn't help either.
cors: {
origin: true,
allowedHeaders: ['Authorization', 'Content-Type', 'apollographql-client-name']
},
Any inputs and suggestions are welcome!
Issue is resolved.
We had kubernetes ingress layer on top of our Apollo Server and that's what was causing changes not to reflect. After we enabled cors on nginx ingress, we were able to make successful calls.
I'm running locally both a Vue Cli 3 app and a Google Cloud Function (CF).
I have changed the response headers in CF as follows:
res.set('Access-Control-Allow-Origin', "*")
res.set('Access-Control-Allow-Methods', 'GET, POST')
and it serves me well when I call the CF from a browser.
For some reason, the same call is CORS blocked when invoked inside the Vue app.
I tried with Firefox (CORS enabled by settings as well as using a plugin).
I also added the following to vue.config.js as described here:
// vue.config.js
module.exports = {
devServer: {
proxy: 'http://localhost:8010', //<-- my CFs are running on 8010
}
}
Not sure how to proceed as the whole point of CFs is to not have any servers running (including a proxy).
Any pointers are much appreciated, cheers.
Problem was with the local Cloud Function emulator.
Got it working when I altered the Cloud Function headers in the live environment.
// Set CORS headers for preflight requests
function setCorsHeaders(req, res){
res.set('Access-Control-Allow-Origin', CLIENT_URL);
res.set('Access-Control-Allow-Credentials', 'true');
if (req.method === 'OPTIONS') {
// Send response to OPTIONS requests
res.set('Access-Control-Allow-Methods', 'GET,POST');
res.set('Access-Control-Allow-Headers', 'Content-Type');
res.set('Access-Control-Max-Age', '3600');
res.status(204).send('');
}
}
I have been trying to figure out how to get this Vue project to work with the Lyft API. I have been able to get an Auth Token successfully created from the three-legged procedure, but I am unable to get the available drive types https://api.lyft.com/v1/ridetypes endpoint from the localhost:8080. It does work on Postman.
It keeps stating:
Access to XMLHttpRequest at
'https://api.lyft.com/v1/ridetypes?lat=37.7752315&lng=-122.418075'
from origin 'http://localhost:8080' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
I had tried doing a proxy using a vue.config.js file:
module.exports = {
devServer: {
proxy: {
'/lyftapi': {
target: 'https://api.lyft.com/v1',
ws: true,
changeOrigin: true
}
}
}
}
I been around other parts of Stack Overflow, and this is the closest thing to my problem, but no answers.
CORS error in Lyft API started recently
Any suggestions?
Axios Get Call
axios.get('/ridetypes', {
baseURL: 'https://api.lyft.com/v1',
headers: {
'Authorization': this.lyftToken,
},
params: {
lat: lat.toString(),
lng: long.toString()
}
})
If it means anything, I am able to make successful GET calls to retrieve Uber products, but not so much the Auth Token (unless its from Postman).
Lyft-API has disabled CORS, this means that browsers will block calls to api.lyft.com.
Vue won't be able to do anyting about this as this is a browser security policy.
Luckily there is nothing from stoping you to make this call from your own server.
One solution is to forward the request and response using your own server. You make a call to your server, the server makes a call to lyft, waits for the response and then responds your request.
This is not a vue only solution.
i'm new in vue.js
i wrote an method for posting data and get page address (get and post) like this
updateCategory() {
this.$eventBus.$emit("loadingStatus", true);
this.$axios.get("http://rimonbd.com/tutorial/api/update-category", this.clickedCategory)
.then(res => {
this.$eventBus.$emit("loadingStatus", false);
this.showingAddModal = false;
if (res.data.error) {
this.$iziToast.error({
title: 'Error',
message: res.data.message,
});
} else {
this.$iziToast.success({
title:'Succes',
message:res.data.message,
});
and i got this error :'(
Access to XMLHttpRequest at 'http://rimonbd.com/tutorial/api/get-category' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
how should i fix that ?
The website you're trying to request data doesn't allow requests from different domains. You're on localhost:8080 requesting data from and external website.
You can try
Use local data to test your project
Deploy your project under the same domain of your data.
Read more about CORS https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Try a hack, only for tests, don't put this in production https://cors-anywhere.herokuapp.com/
example:
this.$axios.get("https://cors-anywhere.herokuapp.com/http://rimonbd.com/tutorial/api/update-category", this.clickedCategory)