NuxtJs Page Redirection With Backend - go

I am building a website that include payment option with NuxtJs. But I am getting CORS error when i want to rediect to payment page of virtual POS integrator.
On backend side I am using Golang/Echo like this:
func startPaymentProcess(c echo.Context) {
header := c.Response().Header()
header.Add("Access-Control-Allow-Origin", "*")
header.Add("Access-Control-Allow-Methods", "DELETE, POST, GET, OPTIONS")
header.Add("Access-Control-Allow-Headers", "Content-Type, Authorization")
//...
// do some controls
//..
c.Redirect(http.StatusSeeOther, "https://web-test.vercel.app/workplace/payment/success")
}
On frontend axios call like this
export const SetSubscription = async () => {
try {
return await axios({
method: "GET",
url: API_URL + `/workplaces/payment-test`,
headers: {
"Authorization": shared.getAuthorizationHeader()
}
});
} catch (error) {
return error
}
}
On developer console error like this:
Access to XMLHttpRequest at 'https://web-test.vercel.app/workplace/payment/success' (redirected from 'https://api.test.domain.tech/workplaces/payment-test') from origin 'https://web-test.vercel.app' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
688030a.js:2
GET https://web-test.vercel.app/workplace/subscription/success net::ERR_FAILED
On developer console network error like this:
enter image description here
Which point that I'm missing?

Try adding withCredentials: true to the axios request's options

Related

Access to fetch at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

I have this api (method get) that is connected to a lambda function that does a simple select from a database, if i test the endpoint with postman with a null body it does work (if i understood, postman is not under the same CORS policy), as well as typing the endpoint on the browser.
But when i try to do a fetch from a simple js, i get the error :
Access to fetch at '...' from origin 'http://localhost' 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.
I enabled CORS in API Gateway, both with the Enable CORS option
and with the Enable API Gateway CORS when creating a new resource
If i test my endpoint with gateway, i also get that Allow-content-allow-origin : * is in my response header :
What should i do to fix this problem?
here is the JS fetch :
console.log("pre fetch");
Show();
console.log("post fetch");
function Show(){
fetch("...").then(onResponse);//.then(onJson);
}
function onResponse(response){
console.log(response);
return response.json();
}
I removed the onJson to avoid confusion, but even with that in its the same problem.
Try to include that in your function too, like this,
I hope this would work:
const headers = {'Content-Type':'application/json',
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Methods':'POST,PATCH,OPTIONS'}
const response = {
statusCode: 200,
headers:headers,
body: JSON.stringify(X),
};
return response;
Here X is the response that you want to return.
If you are using Node.js you needs to install cors.
npm install cors.
After installing cors, include it in the page where you are using fetch function as shown below;
const cors = require('cors');
app.use(cors());
and the error will be solved.
I made a video on how to fix this.
You need to go into the Lambda function and add special code:
original (does NOT work):
exports.handler = async (event) => {
// TODO implement
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
new one, that works:
exports.handler = async (event) => {
// TODO implement
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET"
},
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
You can find this solution in here: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html
Only you need to replace the:
"Access-Control-Allow-Origin": "https://www.example.com",
with
"Access-Control-Allow-Origin": "*",
Special thanks to user, KnowledgeGainer
ALSO, you need to enable CORS on Gateway API side, just follow instruction from here: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors-console.html

Adding multiple headers to graphql client (apollo-boost)

const client = new ApolloClient({
uri,
onError: (e: any) => {
console.log('error: ', e); // Failed to fetch
console.log(e.operation.getContext()); // it does show it has x-abc-id
},
request: operation => {
const headers: { [x: string]: string } = {};
const accessToken = AuthService.getUser()?.accessToken;
const activeClientId = UserService.getActiveClientId();
headers['x-abc-id'] = activeClientId;
if (accessToken) headers['Authorization'] = `Bearer ${accessToken}`;
operation.setContext({ headers });
}
});
The problem here is when i just add Authorization header it makes the POST call and shows the expected error.
But when i add x-abc-id header which is also expected by backend it only makes OPTIONS call (no post call)
P.S. On postman adding both headers works completely fine.
Found what the issue was, thought to share if it help.
Postman does not perform OPTIONS call before sending request to backend.
In OPTIONS call, 👇represents what client call contains: [authorization, content-type, x-abc-id]
BUT what does server expects: 👇
Just authorization, content-type
So it's a calls headers mismatch (nothing related to Apollo).
x-abc-id header explicitly has to be allowed in CORS configuration on backend.
Thanks to Pooria Atarzadeh

I'm getting "blocked by CORS policy" when I try to call Instagram API using Axios [duplicate]

This question already has answers here:
Access-Control-Allow-Origin with instagram api
(1 answer)
CORS error, when i use instagram API with angularjs
(1 answer)
Closed 3 years ago.
I'm trying to fetch some images from my Instagram account in a Laravel application with Vue as front end. When I try to do it in a standalone Vue app, it works well, but when I do so with Laravel, I got a message saying "has been blocked by CORS policy: Request header field x-csrf-token is not allowed by Access-Control-Allow-Headers in preflight response."
I'm using Laravel 5.8 and the Vue and Axios that comes within in and I'm using Homestead as my localhost server.
I've tried a lot of tips that I found here and on Google but I had no success. Basically, I'm trying the very basic of Axios call
beforeMount() {
axios.get('https://api.instagram.com/v1/users/self/media/recent/?access_token=[MY_ACCESS_TOKEN]').then(response => console.log(response))
}
I already created a Cors middleware on Laravel and tried a lot of headers settings on Axios.
I'm basically trying to retrieve a list of my Instagram posts and bypass that cors / x-csrf error.
Laravel automatically applies the X-CSRF-TOKEN header to all axios requests. This is so you can communicate with your application without having to pass the CSRF token every time for POST, PUT, DELETE, etc.
resources/js/bootstrap.js (default settings)
/**
* Next we will register the CSRF Token as a common header with Axios so that
* all outgoing HTTP requests automatically have it attached. This is just
* a simple convenience so we don't have to attach every token manually.
*/
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
You should be able to remove the offending header by doing something like this:
beforeMount() {
// create a new instance so we don't delete the csrf token for other requests
let instance = axios.create();
// delete the x-csrf-token header
delete instance.defaults.headers.common['X-CSRF-TOKEN'];
// use the new instance to make your get request
instance.get('https://api.instagram.com/v1/users/self/media/recent/?access_token=[MY_ACCESS_TOKEN]')
.then(response => console.log(response))
}
Your AJAX request to the Instagram API endpoint has to be sent as a jsonp request which means the dataType of the request has to be jsonp.
This blob in axios repository contains an example of sending a request using jsonp which is mentioned below.
Install jsonp package, if you haven't already.
npm install jsonp --save
and then;
const jsonp = require('jsonp');
jsonp('http://www.example.com/foo', null, (err, data) => {
if (err) {
console.error(err.message);
} else {
console.log(data);
}
});
Below is an example of sending a request using jQuery method with jsonp dataType to the Instagram API endpoint.
$.ajax({
url: "https://api.instagram.com/v1/users/self/media/recent/?access_token=[MY_ACCESS_TOKEN]",
type: "GET",
crossDomain: true,
dataType: "jsonp",
success: function(response){
console.log(response);
}
});

Magento 401 on API request after setting headers for cross origin

I am trying to call the web API for products in Magento from a React Native app. After other stack exchange question & answers plus tutorials I am still receiving a 401 response. I know the call works because I can make it through postman.
Update: So I did not solve it, however I have found that if I use axios the request will work. This seems to be an issue with fetch.
.htaccess mod_headers.c settings
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
Header set Access-Control-Allow-Methods "POST, GET, PUT, OPTIONS"
app/etc/env.php
'x-frame-options' => 'CROSS-ORIGIN'
API Call from React Native
fetch(
'http://localhost:8888/magento/rest/V1/products?searchCriteria[filter_groups][0][filters][0][field]=name&searchCriteria[filter_groups][0][filters][0][value]=product name',
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authentication: 'Bearer fwynACCESS_TOKENbal9tfr'
}
}
)
.then((res) => {
if (res.status !== 200 && res.status !== 204)
reject({ message: 'There was an error with the products service' })
resolve(res.json())
})
.catch((err) => reject(err))
This also includes a web integration named Customers with all the API options set as accessible.

Request header field X-CSRF-TOKEN is not allowed by Access-Control-Allow-Headers

I'm making a get request to embed.rock using vue and axios.
axios({
method: 'get',
url: 'https://api.embed.rocks/api?url=' + this.url,
headers: {
'x-api-key': 'my-key'
}
})
When I use a CDN to get vue and axios with an inline script my code works fine and I get a response back.
When I reference the installed vue and axios scrpts with an external script the code no longer runs and I get the following error:
Failed to load https://api.embed.rocks/api?url=https://www.youtube.com/watch?v=DJ6PD_jBtU0&t=4s: Request header field X-CSRF-TOKEN is not allowed by Access-Control-Allow-Headers in preflight response.
When I click on the error in the console it just brings me to:
<!DOCTYPE html>
Laravel is setting a global configuration to include automatically the X-CSRF-TOKEN in the headers of the request in your bootstrap.js file.
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
Therefore, if you want to remove the token, you can achieve it like this:
var instance = axios.create();
delete instance.defaults.headers.common['X-CSRF-TOKEN'];
instance({
method: 'get',
url: 'https://api.embed.rocks/api?url=' + this.url,
headers: {
'x-api-key': 'my-key'
}
});
the problem is that by default the CSRF Token is register as a common header with Axios so
to solve this issue :
1- replace these lines in bootstrap.js
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-
token');
}
by this line
window.axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
2- install qs module by npm ..... using thie link : https://www.npmjs.com/package/qs
3- define const of qs like below :
const qs = require('qs');
4- use axios by defult like this :
axios.post('your link here ',qs.stringify({
'a1': 'b1',
'a2 ':'b2'
}))
.then(response => {alert('ok');})
.catch(error => alert(error));

Resources