Send axios fetch to domain name, and resending it to API
I want to solve a problem with react native and iphone. I have API on Gcloud let say ip 34.xx.xx.xx, and a domain name myapp.com. On domain name myapp.com I have SSL sertificate and https, on ip address i have nginx server with https to but without sertificate. What can i do to make axios fetch request to my domain name, without getting CORS errors etc.
One way I solved problem with CORS is nginx settings:
# Wide-open CORS config for nginx
#
location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
#
# Om nom nom cookies
#
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
}
With this settings CORS errors disapeared, API stoped sending data, and in Postman i get this error: Postman error screenshot
And this is fetch request:
axios.post(`${Ip}login`,
{
email: email,
password: password
},
{headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
})
.then(function (response) {
const stringToken = String(response.data.access_token)
setToken(stringToken)
sighIn(stringToken)
setLoading(false)
})
.catch(function (error) {
console.log("login section")
Solution 1:
you can use create function of axios
const instance = axios.create({
baseURL: 'https://myapp.com',
headers: { 'any': 'any' },
timeout: 1000,
});
instance.get("/any")