I'm using react-router as following in the App.js file:
<Route exact path="/category/:categoryId">
<ProductLists />
</Route>
and is been called like this:
<RouterLink to={`/category/${category.id}`}>
{category.name}
</RouterLink>
But the problem is that when I'm trying to make the HTTP request inside the ProductLists component, it tries to put the "category" in the beginning for the request.
This is the code that makes the request:
Axios.get(
`/api/resources/products/category-id/?categoryId=${categoryId}`,
{
headers: {
'Content-Type': CONTENT_TYPE_JSON_VALUE,
},
}
So instead of doing this:
http://localhost:3000/api/resources/products/category-id/?categoryId=10a49ef4
it is doing this:
http://localhost:3000/category/api/resources/products/category-id/?categoryId=10a49ef4
Any idea why the "category" is inserted at the beginning of the request?
Thanks!
Thanks to #Yousaf I found the answer.
I just had to add baseURL: '/' like this
Axios.get(
`/api/resources/products/category-id/?categoryId=${categoryId}`,
{
baseURL: '/',
headers: {
'Content-Type': CONTENT_TYPE_JSON_VALUE,
},
}
Hope this will help someone in the future
Related
I'm trying to use react-axios to query a graphql endpoint but I'm encountering a problem with CORS.
Access to XMLHttpRequest at 'https://rickandmortyapi.com/graphql' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Here it is my setup:
const characterQuery = `{
characters(page: 2, filter: { name: "rick" }) {
info {
count
}
results {
name
status
species
gender
image
}
}
}`
const axiosInstance = axios.create({
data: characterQuery,
headers: {"Access-Control-Allow-Origin": "*"}
})
<AxiosProvider instance={axiosInstance}>
<Post url="https://rickandmortyapi.com/graphql">
{(response: any) => {
console.log(response);
}}
</Post>
</AxiosProvider>
Can someone help me? Thanks
CORS is a pain, always, the problem is that the header you pass is the one the server should give you.
You can't force the server to pass the header if they don't already, that the whole point of this protection, avoiding hacker pretending to be other ppl websites.
So the API you are trying to reach must have the CORS header or it will not work
You can play around with fetch see if you have better luck than axios.
Fetch provide some amount of control over your CORS settings, https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
fetch('https://rickandmortyapi.com/graphql', {
method: 'POST',
mode: 'cors',
headers: { "content-type": "application/json" },
body: JSON.stringify({
query: `{
character(id: 1) {
name
}
}`
})
})
This request work with fetch for me, uppon testing, if the content-type was not set to application/json the server failed with error 500 instead of showing a 400 bad request
Edit again, it works with axios too, are you sure you get a CORS error ?
I faced, Refused to set unsafe header "User-Agent" issue while trying to make get request using woocommerce rest api v3. I want to make get request by using axios modifying the header. So How to do this using this code below from axios?
const woocommerce = new WooCommerceRestApi({
url: process.env.REACT_APP_WP_URL,
consumerKey: process.env.REACT_APP_WP_KEY,
consumerSecret: process.env.REACT_APP_WP_SECRET,
version: 'wc/v3',
axiosConfig: {
headers: {},
},
})
Try adding "Content-Type": "application/json;charset=UTF-8" to the headers like so:
const api = new WooCommerceRestApi({
url: url,
consumerKey: consumerKey,
consumerSecret: consumerSecret,
version: "wc/v3",
axiosConfig:{
headers:{
"Content-Type": "application/json;charset=UTF-8"
}
}
});
I've started to build a project using WooComeerce and React.js, but I have one question.
When I try to get the data, for example: "products", received an issue 401 unauthorized..
I've tested my request into Postman/Insomnia and everything is working as expected. I think the problem is coming from the headers part, but for now I can't handle the issue..
Also my response headers are empty!
Here is my code:
const getProducts = async () => {
const response = await fetch(`${process.env.REACT_APP_API_URL}products?consumer_key=${process.env.REACT_APP_API_CONSUMER_KEY}&${process.env.REACT_APP_CONSUMER_SECRED_KEY}`,
{
method: "GET",
mode: "cors",
credentials: "include",
headers: {
"Authorization": `Basic ${process.env.REACT_APP_API_CONSUMER_KEY}`,
"Content-Type": "application/json",
},
}
);
return response;
};
How can i fix that issue?
Note: I'm not using WooCommerce REST API package.
Thank you in advance!
Usually the basic auth string is base64-encoded string username:password. However i see the consumer key being used in the req and the header. Can you please double check your authorization header?
I would like to get an HTML page this one :https://cas.univ-lemans.fr/cas/login, but my response haven't body....
Anyone have a idea ?
my code :
this.header = {
"Access-Control-Allow-Origin": "*",
"mode": "no-cors",
"Content-Type" : "text/html"
};
fetch(url, this.header)
.then(function(response){
console.log(response);
response.text();
})
.then((body) => {
console.log(body);
})
console :
As per the response object in the console, response.ok is false that is why you are receiving body for it. Also as per the warning, there is a Cross-Origin issue in fetching the resource. Kindly, go through the following CORS origin link to understand how it works and how you can configure it.
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS.
Also as your issues looks to be similar to CORB, it will better if you have a look in the CORB security implementation and how you can by pass it.
https://www.chromium.org/Home/chromium-security/corb-for-developers
I'm using react-router for server side rendering and I have locale information stored in a locales.json file. The locale information is only set after a response from an api call, which includes the current language, i.e. 'GB', 'NO', 'FR', etc., which then completes the server response and everything is fired through to the client in the correct language.
However, I'm using the react-router match method:
match({ routes, location: req.url }, (error, redirectLocation, renderProps) => { ... }
...and I need the routes to be based off the language from the api response, i.e.
// Route
<Route path={`:storeId/${locales[language].path}`} />
// locale.json
{
"GB": {
"path": "contact"
},
"NO": {
"path": "kontakt"
}
}
Is this approach possible? It's like I need to define routes after the api call is made, but to make the api call, I need routes defined.
Yes, I haven't tried your example specifically, but it is definitly possible to define routes from an api response and pass it to the "match" function.
You could try something as following:
function handleServerRendering(req, res) {
axios.get('http://localhost:3001/myCutomeRoutes')
.then(function(response){
const myRoutes = {
routes: response.data,
location: req.url
}
match(myRoutes, function(error, redirectLocation, routeContext) {
// WRITE YOUR CODE IN HERE...
})
})
.catch(function(err){
console.log('error', err);
})
}
As you can see, you firstly do an API call and then you pass the response.data to routes inside "myRoutes" constant