React - Getting 401 authorization and CORs preflight error when trying to access a Kubernetes API endpoint using Axios - reactjs

My React host has an IP of 10.60.160.61.
The API endpoint that I'm trying to reach has an IP of 10.200.50.21.
My App.js:
useEffect(() => {
const fecthPods = async () => {
try {
const response = await axios.get(`https://kubernetes.endpoint.com/k8s/clusters/name/v1/pods/myproject`,{ headers: { 'Authorization': 'Bearer token-myToken' } })
console.log(response.data)
} catch (err) {
if (err.response) {
// Not in the 200 response range
console.log(err.response.data)
console.log(err.response.status)
console.log(err.response.headers)
} else {
console.log(`Error: ${err.message}`)
}
}
}
fecthPods()
},[])
I get two errors in the network tab of developer tools:
401
CORS preflight
I can access an external API endpoint with no issue (ie. https://pokeapi.co/api/v2/pokemon/ditto).
I can successfully run a curl command to the Kubernetes API endpoint by passing the Auth token in the headers parameter, but just not working with Axios.
I don't think I need to run a backend express server since the API endpoint that I'm trying to reach is not on my localhost.
Not sure what else to try.

I believe I have found the answer to this question. Seems like I will need to run my API calls through a custom proxy as mentioned in this post.

Related

How to hide authorization bearer token from header?

I want to hide some information such as bearer token and API key in header. I have been heard about ssr and using proxy to hide that information, but how? Can someone tell me how to do that? Or is that possible to do in client side?
I tried with some ssr that fetch in react, but it doesn't work for me. I also tried with proxy, but that works for API key that didn't need a dynamically params like user token.
To use server-side rendering (SSR), you will need to install and import the following packages: express, cors, and Axios. The cors middleware allows for Cross-Origin Resource Sharing, while Axios is used to make HTTP requests to external APIs or databases, and handle the response data asynchronously. By setting the headers with Axios, you can pass along sensitive information such as API keys and bearer tokens. After receiving the data back, you can destructure it from the Axios response and then send it back to your users by using the res.json() method.
const cors = require('cors');
const axios = require('axios');
const app = express();
app.use(cors());
app.get('/api/data', async (req, res) => {
try {
const { data } = await axios.get('https://api.example.com/data', {
headers: {
Authorization: `Bearer ${process.env.BEARER_TOKEN}`,
'API-Key': process.env.API_KEY,
},
});
res.json(data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});

Axios returns NetworkError / CORS Headers enabled

I build a ionic-react android application with Axios to get a server response. Two weeks ago my code was working fine. Now the axios request always returns a NETWORK_ERR (HttpError or Axios Error).
I tried to use all CORS Headers possible in my api, but the request is not sent to the webservice.
I hope anyone can help me:
This is the Code I was using:
const api = axios.create({
baseURL: "http://192.168.0.145:8080/RestFulTest-1.0-SNAPSHOT/api",
});
function callApi(){
api.get("/verification")
.then((res) => {
console.log(res);
})
.catch((error) => {
console.log(error);
});
}
Just directly opening the API Url in browser is not loading it...
Sot it seems either the backend is down or blocking and requires an authorization header with the axios request, like
let tokenStr = "Your TOKEN";
axios.get("/verification", { headers: {"Authorization" : `Bearer ${tokenStr}`} });
Hope it helps..

Cannot make a GET request in Postman with React

I created a joke generator app that takes jokes from a local json file with data that I created and displays it in the browser. This app has no backend at all. I am trying to make a GET request through Postman, but no luck. Is it even possible to use postman in this scenario?
NO Postman is not used for programmatic api calls. Use axios for this. Suppose your server is running on localhost:3000.
npm install axios
In your component,
const axios = require('axios');
// Make a request for a user with a given ID
axios.get('/jokes?id=1')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});

How can i access the cookie sent as a response from express in react js?

I am using mern stack to make an application. For authentication i am using toke auth with passport authentication and for security reasons i am sending token in cookie. I have a login call which returns a cookie with response. The snippet is below:
res.cookie("cookie_token", token, { maxAge: 84600 });
res.send({
status: "success"
});
I can see the cookie in postman and even in browser in network(xhr request).
I am using axios for making call to the login api in react js.
axios.get(myapiurl, {
headers: {
email: fields.email,
password: fields.password,
"access-control-allow-origin": "*"
}
})
.then(res => {
console.log(res);
}).catch((err) => {
console.log(err);
});
Though i can't find a snippet to access the cookie in react js. How can i parse it? I can't see cookie in response of axios though? How can i access it.
Please try this. Snippet from mdn.
function getCookie(sKey) {
if (!sKey) { return null; }
return document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + sKey.replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1") || null;
}
export function getLoginInfo() {
const cookieToken = getCookie('cookie_token')
console.log(cookieToken)
}

How to ignore SSL issues in axios using React Native?

Hi I'm currently working with react native on Android with Expo. I am trying to send requests to my server which has a valid ssl certificate, but for some reason axios takes it as invalid, so axios does not allow me to send requests to my server's api.
this is the error i get:
Error: Network Error
So I wonder if there is any way to make axios ignore the problem with the ssl and can send the requests in a normal way
this is my code:
try {
const headers = {
'Accept-Language': 'es-ES,es;q=0.8',
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json",
};
axios.get("https://URLtoMySERVER", {}, headers)
.then(response => {
console.log(response)
const posts = response.data;
console.log(posts)}
).catch(function(error) {
console.log("error", error);
});
} catch (error) {
console.log('err', error);
}
some points that I want to clarify:
1- I can't use RNFetchBlob because I'm using Expo, and RNFetchBlob have some native libraries.
2- I can't use httpsAgent either with axios because apparently https library does not work with expo, or at least it does not work for me.
3- fetch doesn't work either
Is there any other alternative to axios or fetch that works in react native with expo and where you can ignore the problems of https?

Resources