HERE Geocoding API - not working inside my React app - reactjs

I have a React app in which I use the HERE Geocoding API. I have an axios request to retrieve latitude and longitude and it does not work as well as expected. The request is not working inside my app
return axios.get(`https://geocode.search.hereapi.com/v1/geocode?q=${address}&apiKey=myAPIKey`)
I have a 401 error. Bearer token invalid. Bearer missing or bearer value missing. If I open a new tab in my browser and paste the url https://geocode.search.hereapi.com/v1/geocode?q=${address}&apiKey=myAPIKey it works fine and I get the result I need.
I tried using the Authorization header
const config = {
headers: {
'Accept': 'application/json',
'Authorization': `apiKey myAPIKey`,
}
};
return axios.get(`https://geocode.search.hereapi.com/v1/geocode?q=${address}&apiKey=myAPIKey`,config)
In the Authorization header, I tried with Bearer and Basic instead of apiKey
documentation HERE API
In the documentation about how to create an API Key and how to use it, the only thing I need to do is what I have already done. I have created a project, an API Key and I use it in my request.
HERE Geocoding API Key

I don't know how the HERE api works but the error message is probably the answer you are looking for.
You are likely to provide the api key via the Authorization header with your request. Read about the header on MDN

You just need to pass your API key in the link as a parameter.
Just sign up and you can get your API key.
https://developer.here.com/sign-up
The code should be like this.
return axios.get(`https://geocode.search.hereapi.com/v1/geocode?q=${address}&apiKey=${HERE_MAP_API_KEY}`,config)
The latest request would look like this.
axios.get(`https://geocoder.ls.hereapi.com/search/6.2/geocode.json?languages=en-US&maxresults=${maxResults}&searchtext=${query}&apiKey=${HERE_MAP_API_KEY}`)
.then(res => {
const data = res.data
console.log(data)
})
.catch(err => console.log(err))

Related

How to retrieve Authorization header (rails / react app)

Im banging my head and cant solve the mystery :(.
I've rails app and react, rails app returns Authorization bearer token in response header and also it returns Access-Control-Expose-Headers: Authorization
I see in the responses that everything is returned properly, but when I try to get value of Authorization header using response.headers.get('Authorization') Im getting null
My Fetch looks like:
fetch('/users/sign_in.json', {
method: 'POST',
headers: {'Content-Type': 'application/json', 'X-CSRF-Token': token},
body: JSON.stringify({ user: values })
})
.then((response) => console.log(response.headers.get('Authorization')))
.then((data) => console.log(data))
What Im missing?
Ive checked cookies - rails does not save token into cookie, Im using devise-jwt gem. Thanks for any hint.
Problem solved...
When user signs in, in first response he gets Authorization header. I've tried sign in already signed user, and I'didnt get any proper header although in chrome debugger Authorization header was present in response :/

Post Request from axios always returns Unauthorized despite having valid JWT set in header/Axios Deletes Headers

I set up passport-local to login a user, and then once logged in, the user will be given a JWT token through passport-JWT. The JWTStrategy is set up to use
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken() so that the JWT can sent with the Authorization header Authorization: `Token ${userContext.token}`}. In my react client side, I have set up a GET request using axios as shown here:
const fetchProfileDetails = async(config)=>{
const res = await axios.get("http://localhost:8080/users/me", config)
}
const config = {
method:"GET",
withCredentials: true,
headers: {Authorization: `Bearer ${userContext.token}`}
}
This request successfully authenticates and returns the user data from /me.
Now heres the kicker: when I use the exact same request structure, but switch the method to post in the axios request and in my express route in the backend, the request always responds with a 401 Unauthorized.
However, when I send the same request from POSTMAN, with the same Bearer Token used in the request that was Unauthorized, the request succeeds without any errors.
TLDR: GET requests work with the JWT token and return with a 200 status code, while the same request with a POST method returns with a 401 status code.
What am I missing here??!
You are probably using there GET and not using POST anywhere.
In your code, you have code only for get. You will need to write code for post as well.
Below is the code for post for your reference:
router.post('/', config, async(req, res, next) => {
const { error } = validateBody(req.body);
if (error) {
return res.status(400).send(error.details[0].message);
}
const newData= new passport({ name: req.body.name });
await newData.save();
console.log('saving the document');
res.send(newData);
})
Your code should have post as well. Writing single code will not work. You need to have to write code for every condition and every possibility. So like for get need code for post as well, also if you have condition for patch or delete or put you will have to write the axios method for that as well.
Hope this has helped you in any way.
I have come upon a solution for this issue. For some reason, axios was not maintaining the Authorization header I had set in my config variable, and deleted it upon making the request. To solve this, I just had to reshuffle my axios request to look like this:
const res = await axios({
method:'POST',
url:"http://localhost:8080/users/test",
headers:{'Authorization':`Bearer${token}`
}})
I feel cheated as I spent a ton of time on this and the solution was so underwhelming. Axios was trolling me the whole time :/

Autodesk Forge Dataviz NPM Packages - Trying to use React Viewer

I've been trying to develop with the new Forge Dataviz NPM packages for a while but I've been facing errors. I'm currently just trying to load a Viewer (https://forge.autodesk.com/en/docs/dataviz/v1/reference/UI/Viewer/) but I think I'm doing something wrong. Still don't know what.
This is my React const :
const TestAutodesk= () => {
return (
<div>
<Viewer
env="AutodeskProduction"
docUrn="URN STRING"
getToken={async () => await fetch("https://developer.api.autodesk.com/authentication/v1/authenticate",requestOptions)
.then((res) => res.json())
.then((data) => data.access_token)}
></Viewer>
</div>
);
};
These are the requestOptions:
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("client_id", "ID");
urlencoded.append("client_secret", "SECRET");
urlencoded.append("grant_type", "client_credentials");
var requestOptions = {
method: "POST",
headers: myHeaders,
body: urlencoded,
redirect: "follow",
};
The final app is not going to use this as the auth, I'm going use a safe backend endpoint, this is just for trying to get the viewer loaded and the front end done. This is the error I get on the console:
I think the error is that is calling localhost:8080 but it should call an autodesk endpoint. Any idea on this? The Api reference / Dataviz example doesnt say anything about this.
The <Viewer> React component is pretty simple (https://github.com/Autodesk-Forge/forge-dataviz-iot-react-components/blob/main/client/components/Viewer.jsx), and shouldn't itself make any requests to localhost. Are you perhaps making those requests somewhere else in your application?
Regarding the getToken implementation, I'd suggest two things:
It's not a good practice to make these requests directly from the client-side code. This way, someone could potentially steal your Forge client ID and client secret. A better approach is to implement a custom endpoint in your own backend that generates the token with limited privileges, hiding the credentials from the client.
If you need to make the raw request to https://developer.api.autodesk.com/authentication/v1/authenticate, note that it requires 4 (not 3) parameters: client_id, client_secret, grant_type, and scopes.

React and Axios get AWS client credentials

I'm using latest version of react with axios and want to get an authentication token from aws / cognito. Therefore I have my client and client secret. When I send a curl request, it works as expected, but when I send the request via axios, I always get a status 405 response.
My code looks as follows:
...
axios({
url: 'https://xyz.amazoncognito.com/oauth2/token?grant_type=client_credentials',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'client_id': '***************',
'client_secret': '****************'
'redirect_uri': 'http://localhost:4200'
}
})
.then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
Instead of setting client_id, client_secret and redirect_uri to the headers, I added them in the url like
...grant_type=client_credentials&client_id=************&client_secret=*************&redirect_uri=http%3A%2F%2Flocalhost%3A4200
with the same result. Any ideas, what I'm doing wrong? As a side remark: I'm using axios for all my api requests and so I would like to stay at axios also in this case.
Thanks and kind regards,
Balu
You are not passing the required parameters correctly. Have a look at the example here:
https://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html
The required headers will be:
Authorization
If the client was issued a secret, the client must pass its client_id and client_secret in the authorization header through Basic HTTP authorization. The secret is Basic Base64Encode(client_id:client_secret).
Content-Type
Must always be 'application/x-www-form-urlencoded'.
The other information will be passed as request parameters.
This being said, you should not store your client and client secret on the client side (React application). If this is exposed on the client, anyone can get your client ID and Client secret and obtain a Cognito Token.

React - fetching from API, how to skip the cors response

I want to make a simple POST request from my React app to my Spring back-end to authenticate the user. What i am doing :
fetch('http://localhost:8080/login', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
username: this.state.username,
password: this.state.password,
}),
})
.then(response => response.json()).then(resposne => console.log(resposne))
Trying to make this call will get me a SyntaxError: Unexpected end of JSON input. If i log the response i can see that it is a response with a type:cors. I assume i am getting the response from the OPTIONS request that goes out. How can i skip that response? If i check the headers on the response, the header that i want to get, which is the Authorization header, is non-existant. If i go to chrome devtools - network section, and look at the response i am getting, i can see the resposne is as it should be, and i can even see the token returned in the Authorization header. How can i access that header in my React app? Server is properly configured since it returns the token, i just cant get it in the React app.
Thanks!
You should add the Access Control Expose Headers with the Authorization header like so:
Access-Control-Expose-Headers: Authorization
It doesn't seems an error on the token generation. Did you take a look on Response body?
Seems like the response body is not a valid json.

Resources