How do I set CORS headers in vuejs2? - vuejs2

I am using axios a get method. I also have set CORS header, but it keeps giving me error saying Cross-Origin Request Blocked.
Vue.js2:
methods: {
getSliderData () {
axios
.get('/sliders', {
headers: {
'Content-Type': 'Application/json',
'Access-Control-Allow-Origin': '*'
}
})
.then(res => {
console.log(res)
})
.catch(err => {
console.log(err)
})
}
}
Error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/api/sliders. (Reason: CORS request did not succeed).

Related

Cors error - ngrok & express & axios issue when trying to make POST request to the server

I am experiencing an issue when trying to make POST request to the server.
both frontend and backend are ngrok hosting.
this is the POST request:
export async function createTest(test: any) {
try {
const res = await axios.post(
`${backendDomain}/test`,
{id: test, name: 'test'},
{
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
'Access-Control-Allow-Methods': 'POST',
},
}
)
const newTest = res.data
return newTest
} catch (error) {
console.log(error)
}
}
this is the backendDomain: https://sd21-23-221-223-216.ngrok.io
Backend:
const corsOptions = {
origin: "https://dz23-12-256-124-663.eu.ngrok.io",
methods: ['GET', 'PUT', 'POST', 'HEAD', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'Origin', 'Access-Control-Allow-Origin'],
credentials: true,
}
app.use(cors(corsOptions))
Error:
Access to XMLHttpRequest at 'https://sd21-23-221-223-216.ngrok.io/test' from origin 'https://dz23-12-256-124-663.eu.ngrok.io' has been blocked by CORS policy:
Request header field access-control-allow-methods is not allowed by Access-Control-Allow-Headers in preflight response.
More wierd is that I also have GET request which sometimes work and sometimes not.
any ideas?
You need to add this header param ngrok-skip-browser-warning with any value
Example:
$.ajax({
url: 'https://5120-143-202-253-244.eu.ngrok.io/api',
type: 'GET',
headers: {
"ngrok-skip-browser-warning":"any"
},
success: function (data) {
console.log(data);
}
});

has been blocked by CORS policy by using axios and fetch in react [duplicate]

This question already has answers here:
Axios having CORS issue
(12 answers)
Closed 3 years ago.
I'm trying to do a post request of a server but keep getting a CORS error using axios and fetch in React.
the code:
fetch('https://api/entries',
{ mode: 'no-cors',
method: 'post',
headers: {
"Content-Type":"application/octet-stream",
'Access-Control-Allow-Origin': true
},
body: JSON.stringify({
"KEY":"VALUE"
})
})
.then((response) => {
console.log(response)
})
.catch(err => console.log(err))
or
axios({
method: 'post',
url: 'https://api/entries',
headers: {
"Content-Type":"application/octet-stream",
'Access-Control-Allow-Origin': true
},
data: {
"KEY":"VALUE"
}
})
.then(response => {
console.log(response);
})
.catch(err => console.log(err));
axios console response
Access to XMLHttpRequest at 'https://api/entries' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
and the another
Fetch console response
Cross-Origin Read Blocking (CORB) blocked cross-origin response https://api/entries with MIME type text/plain. See https://www.chromestatus.com/feature/5629709824032768 for more details.
Thanks
The best and easiest way is to tackle this problem is to use Proxy URL.
Like so
const PROXY_URL = 'https://cors-anywhere.herokuapp.com/';
const URL = 'https://api/entries';
axios.post(PROXY_URL+URL)
.then( i => console.log(i) )
.catch(e => console.error( "Error occured! ", e));
in your case try using this like this: This should work.
const PROXY_URL = 'https://cors-anywhere.herokuapp.com/';
const URL = 'https://api/entries';
axios({
method: 'post',
url: PROXY_URL+URL,
data: {
"KEY":"VALUE"
}
})
.then(response => {
console.log(response);
})
.catch(err => console.log(err));
You can even use Proxy URL with fetch()
its depends on your backend
for example, if you use Django
you need to install https://github.com/ottoyiu/django-cors-headers
and add this CORS_ORIGIN_ALLOW_ALL=True in setting file

why axios get method request send twice?

I run the axios get method to call php script.but request send twice
how to solve this problem.
myfunction:-
axios.get('http://13.233.179.174/customers_log.php',{
headers: {
'Access-Control-Allow-Origin': '*'
},
})
.then(function (response) {
$("#spinner").hide();
console.log('this is response work');
console.log(response.data);
})
.catch(function (error) {
$("#spinner").hide();
console.log(error);
})
It'a Preflight request
It is an OPTIONS request, using three HTTP request headers: Access-Control-Request-Method, Access-Control-Request-Headers, and the Origin header.
Check here - https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request

Express CORS response

I am using express to return an api response retrieved via a request call.
router.post('/', function(req, res){
var options = {
...
}
rp(options)
.then(function (parsedBody) {
console.log(parsedBody);
res.json(parsedBody)
})
The console log displays the expected payload, also when I use Postman I also see the expected payload.
When though my client app gets the response it is:
Response {type: "cors", url: "http://localhost:3001/api/", redirected: false, status: 200, ok: true, …}
Ive tried adding CORS middleware:
app.use(function(request, response, next) {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers",
"Origin, X-Rquested-With, Content-Type, Accept");
next();
});
My client is a very simple react app using fetch:
fetch('http://localhost:3001/api/', {
method: 'POST',
dataType: 'JSON',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: data,
}).then((response) => {
console.log(response);
}).catch((response) => {
console.log('Error');
});
My react app is localhost:3000 and the express api localhost:3001, the expected payload is a very simple object...
{
athlete: {
firstname: "Matt"
...
}
}
How can I just forward on the api request response to the clients fetch success method?
The problem is not CORS related, the response within the react app needed parsing as json:
.then((response) => {
console.log(response.json());
})

AXIOS : Send Authorization header returns Error 401, Authorization Header missing

I came around this solution but this is not working for me.
Following is my code:
axios.post('http://myurl/api/login', {
email: 'john#doe.com',
password: '123456'
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).then(response => {
if (response.data) {
this.AuthToken = response.data.token
console.log(this.AuthToken)
axios.get('http://myurl/userdetails/:uid', {
uid: 'D123'
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': this.AuthToken
}
}).then(response => {
if (response.data) {
// this.AuthToken = response.data
console.log(response.data)
}
}).catch(error => {
console.log('User Data response Error: ' + error)
})
}
}).catch(error => {
console.log('Login Error: ' + error)
})
I'm getting token from the first POST Login API call. I used that toke to pass into another API call as Authentication token. But I get error: Missing Authorization Headers
Found the solution:
axios.defaults.headers.common['Authorization'] = this.AuthToken;
Try to add another header. "Access-Control-Allow-Headers" : "*".