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');
});
Related
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.
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..
I want a simple authentication with bearer token and rest API which should be stored in local storage and be refreshed in the given time in REACt.
as I know react is a library and tends to do simple work that concerns on Effective UI and Ux. What about HTTPS request stuff and also authentication . I guess Axios should be the fine approach for HTTP request but using third-party library is sick n RWACt especially if you are a beginner who doesn't have a much understanding of promises than react makes you have a nightmare. Any Solution will be great.
Use axios for this purpose. you can use it like this :
axios.post('/login', data)
.then(response => {
localStorage.setItem('token', response.data.token);
});
Also you can use axios interceptors for this purpose. It will run for every request call. for validating and setting headers to requests like this:
const config = {url:'https://...',timeout:10000}
const instance = axios.create({
baseURL: config.url,
timeout: config.timeout
});
instance.interceptors.request.use(
config => {
const token = localStorage.getItem('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
error => Promise.reject(error)
);
I am getting the CORS access error in my React Native app when connecting to an external API.
async componentDidMount() {
// POST request using fetch with async/await
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: JSON.stringify({ type:'accountLookup',storeId:STORE_ID, storeKey:STORE_KEY, memberId:'471324' })
};
const response = await fetch('http://frequent5.revlogical.com/wsMobile', requestOptions);
const data = await response.json();
this.setState({ data: data });
The problem is most likely not with React app, rather with your server which is not configurated to serve your app.
You should set 'Access-Control-Allow-Origin' header on your server to allow your app's address to make requests.
This problem is usually the fault of the backend. Test it with a tool like https://www.test-cors.org/
An alternative is to create a server to be intercepted between the frontend and the API, and you can handle this guy's cors
I am trying to set a custom header on every response my Express api sends, so I wrote a simple middleware:
app.use((request, response, next) => {
response.setHeader("custom-header", "value");
next();
});
But when I inspect the headers received on my ReactJS application using axios interceptor, it simply doesn't appear. Here is my interceptor:
import axios from "axios";
const api = axios.create({
baseURL: "http://localhost:3333"
});
api.interceptors.response.use(
response => {
console.log(response.headers);
return response;
},
error => {
console.log(error)
return Promise.reject(error);
}
);
export default api;
Just in case it may be relevant, my express app also uses cors, helmet and express.json middlewares, but I already tryied removing them and still I wasn't able to receive the header on the client.
What would be the appropriate way to set and receive a custom header on every request?
So ironically a few minutes after posting the question I finally found the solution (which I was looking for for hours):
Turns out it is necessary to configure Access-Control-Expose-Headers on the cors middleware configuration, like this:
app.use(
cors({
exposedHeaders: ["custom-header"]
})
);