request failed with status code 403(forbidden) in axios.get - javascript

i am building a simple lyrics finder app using react.js and using musixmatch api. when i request the api i get this error in consoleError: Request failed with status code 403 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:62)
this is my componentDidMount() function
import React, { Component } from 'react';
import axios from 'axios';
const Context = React.createContext();
export class Provider extends Component {
state = {
track_list: [],
heading: "Top 10 Tracks"
}
componentDidMount() {
axios.get(
`https://cors-anywhere.herokuapp.com/https://api.musixmatch.com/ws/1.1/chart.tracks.get?chart_name=top&page=1&page_size=5&country=it&f_has_lyrics=1&apikey=${
process.env.REACT_APP_MM_KEY}`
)
.then(res => console.log(res.data))
.catch(err => console.log(err));
}
render() {
return (
<Context.Provider value={this.state} >
{this.props.children}
</Context.Provider>
);
}
}
export const Consumer = Context.Consumer;

status code 403 means that you are not authorized. You could either have entered a wrong api key or maybe your process.env does not work (try to enter the api key directly!).
And are u sure that you need cors-anywhere? Did you try without?
EDIT:
you can test if your api key works when you simply enter the url with your key into the browser (without cars-anywhere) like so:
https://api.musixmatch.com/ws/1.1/chart.tracks.get?chart_name=top&page=1&page_size=5&country=it&f_has_lyrics=1&apikey=your_api_key
EDIT 2:
this works, when I try it inside a React application: So the problem must be at your process.env implementation.
componentDidMount() {
axios.get(
`https://cors-anywhere.herokuapp.com/https://api.musixmatch.com/ws/1.1/chart.tracks.get?chart_name=top&page=1&page_size=5&country=it&f_has_lyrics=1&apikey=your_api_key`
)
.then(res => console.log(res.data))
.catch(err => console.log(err));
}

From my experience, it was problem with axios version. so if you tried all solutions and still can not find the root cause, you can try to change axios version. I was using was assume role credentials to make a request against a service and always getting rejected with 403 even though the credentials were correct. I was using axios 1.3.1 but then I downgraded it to 0.27.2 and now my code is working fine

If you are not using an API key, you might have exhausted your request. You only get about 50 request thereabout per hour or something like, except you use an API key

Related

I do not know why I can't access open ai's api for use in a react app

I am trying to access openai's api for a react application. I am getting an "unsafe header" error, an error 400, and at the same time "https://api.openai.com/v1/completions" is sending me a prompt about not providing my api key, even though I am providing the api key through a .env file. I do not know what to do, and I'm wondering what exactly I did wrong.
This is the react function I am using:
const configuration = new Configuration({
apiKey: process.env.REACT_APP_OPENAI_API_KEY,
organization: "org-xut9Kn1LqNLyDiHEMAQlnJ0k"
});
const openai = new OpenAIApi(configuration);
const handleSuggestions = async (text) => {
const response = await openai.createCompletion({
model: "text-davinci-001",
prompt: "autocomplete this word, letter or sentence: " + text,
max_tokens: 100,
n: 1,
stop: text.length - 1,
temperature: 0.15,
});
console.log(response);
const data = await response.json();
setSuggestions(response.choices[0].text.split(' ').slice(text.split(' ').length - 1).join(' ').split(' '));
};
``
I am getting a "unsafe header "User-Agent"" error as well as an error 400 from "https://api.openai.com/v1/completions" in my browser console while running the react app. This is the full prompt I am getting back from "https://api.openai.com/v1/completions":
{
"error": {
"message": "You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth (i.e. Authorization: Bearer YOUR_KEY), or as the password field (with blank username) if you're accessing the API from your browser and are prompted for a username and password. You can obtain an API key from https://platform.openai.com/account/api-keys.",
"type": "invalid_request_error",
"param": null,
"code": null
}
}
Please what can I do, and what exactly is wrong with the code? Also, hoping this counts as a "Minimal, Reproducible Example", as I am pretty new to stack overflow.
You should be making the request from a server not your client.
Ajax request: Refused to set unsafe header
I highly recommend checking out Next.js 13 as it uses React under-the-hood and let's you create "Server" components that are essentially isomorphic.
Here's an example Next.js 13 app/pages.tsx file:
const App = async () => {
console.log("App.js");
const results = await fetch(
`http://api.weatherapi.com/v1/forecast.json?key=<API_KEY>&q=Stockholm&days=6&aqi=no&alerts=no`
);
const json = await results.json();
console.log("json", json);
return (
<>
<h3>{json.location.name}</h3>
<p>{json.location.temp_c}</p>
<p>{json.location.localtime}</p>
</>
);
};
export default App;
Check out this working Next.js 13 / React18 sandbox which hits the Weather API - If you'd like fork it and see if your API calls work on the server inside this app.pages.tsx file. Otherwise you will need to use a Firebase Function or some backend server.

Why does Axios keep sending Network error on React Native

I am currently working on a React Native project.
My code is this:
const onSubmit = async ({email, password}) => {
const url = 'https://gravitee.****.com:***/***/api/auth/signin';
try {
const response = await axios.post(url, {
email,
password,
registrationSource: SOURCE,
});
console.warn(response);
} catch (error) {
console.warn('err: ', error);
}
};
I have made this project on React as well and this is working well there. But on React Native it gives me Network Error. Nothing else. I tried with fetch api, it didn't work either. And what's interesting is I can fetch data from an external api that I just found on web. So what could be the problem? By the way i am running app on ios simulator and my device is Mac M1
Full error is like this:
err: AxiosError: Network Error
Call Stack
onSubmit
index.js: 87:7
asyncGeneratorStep
asyncToGenerator.js: 3:16
\_throw
asyncToGenerator.js: 29:27
tryCallOne
internalBytecode.js: 53:16
anonymous
internalBytecode.js: 139:27
I tried sending request to gravitee with axios and fetch and expecting login data of the user.

SvelteKit Hook Prevents Endpoint Request

Trying out SvelteKit and I'm having a hard time with hooks. The docs don't really seem to explain it all too well. My current understanding of hooks is that they basically allow you to interact with requests made to your server before they get to their destination? (I'm open to a better explanation - specifically the handle hook).
My current issue is I made an endpoint called login. As the name suggests, it allows users to sign into my application by generating a token and storing it as a cookie on their client. This works until I add hooks. After reading the hooks description, I figured the handle hook is perfect for what I want to do - validate the token on each request - if invalid, reroute the user to the login screen, if valid, allow the request to continue uninterrupted.
export const handle: Handle = async ({ event, resolve }) => {
const isLogin = event.url.pathname.startsWith('/login')
const cookies = cookie.parse(event.request.headers.get('cookie') || '');
const token = cookies['token']
if (!token) {
if (!isLogin) {
return Response.redirect(`${event.url.origin}/login`)
}
return await resolve(event)
} else {
try {
await verifyToken(token)
if (isLogin) {
return Response.redirect(`${event.url.origin}/about`)
}
} catch (err) {
return Response.redirect(`${event.url.origin}/login`)
}
}
return await resolve(event)
};
This does not work as expected. When I initiate the request to the api/login endpoint, the request does not seem to make it there. I have console.logs all over the endpoint but no messages were outputted to the terminal & when I check the application storage, no new cookie was added.
What am I missing about hooks?
Why is it not passing the request off to the endpoint?
Any idea how I can fix this?
The handle hook runs for every request—including endpoints.
When you fetch /api/login without a token, your hook will redirect the request to /login since isLogin === false. You need to allow through every route that should be accessible without a login, for example:
const isLogin = /^\/(api\/)?login$/.test(event.url.pathname)

Best place to fetch data for authed users in Vue app?

Hi I'm fetching a arrays of posts from my express API in the Home.vue which is protected by route guards.
<script>
export default {
created() {
this.$store.dispatch('fetchPosts')
}
}
</script>
fetchPosts action:
async fetchPosts(context) {
try {
const res = await api.get('/posts', {
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`
}
})
context.commit('SET_POSTS', res.data)
context.commit('SET_ERROR', null)
} catch(err) {
console.log(err.response.data)
context.commit('SET_ERROR', err.response.data)
}
}
In my action I commit a mutation which sets the posts object to res.data. I only want to fetchPosts when user logs in since I have a mutation which adds the post to the db and updates the posts state, when user adds a post. But because I route back to the home screen this causes the created() hook to run again, re-fetching data on each post req. App of course work fine but could be more efficient. What can I do to resolve better enhance my app?
You could check that you do not already have the state populated.
If it's empty make the API call, otherwise do nothing.
Having guards is a good thing. Depending of your app and the way you want to handle authed users, you could also wire a global middleware to your router. This will add more generic code and could be used on several places, hence less errors/duplication.
Here is an interesting article about this: https://markus.oberlehner.net/blog/implementing-a-simple-middleware-with-vue-router/
The rest of your code looks fine!

Axios always runs .then with invalid url

I am using axios to make a HTTP get a call, if I specify an invalid URL axios runs the .then() as if it was successful. How to I get it to error if it can't find the url
import React, { Component } from "react";
import axios from "axios";
export default class AxiosRequest extends Component {
render() {
axios
.get("invalidurl")
.then(response => {
console.log("Axios request successful...or was it, No it wasnt");
})
.catch(err => {
console.log("Axios request error", err);
});
return <h1>Axios Request</h1>;
}
}
Running sandbox to show the issue.
https://codesandbox.io/s/9lmn7316kp
The reason for this is if you open the "Network" console in you web browser, you will see the request being made is to the webpage you are currently on (the sandbox), thus returning a 200. If you put in a real url such as http://google.com/ you will see the correct return.

Categories