I have a django api (djangorestframekwork, django2.1, python 3.6) that I run locally - http://127.0.0.1:8000/api/cards/b361d7e2-6873-4890-8f87-702d9c89c5ad
. This api seems to work well. I can hit it via the web api or use curl/requests to add to or view the database.
Now, I want to be able to have my React project hit this api. I can have my react project hit a different api and it returns the data, but when I replace that URI with my own URI it breaks.
App.js - there is one line commented out. Switch that out with the other to switch between the public and private api.
import React from 'react'
import keyforge from '../api/keyforge'
import localhost from '../api/localhost'
import SearchBar from './SearchBar'
class App extends React.Component {
onSearchSubmit = async (term) => {
const response = await localhost.get("api/cards/" + term)
//const response = await keyforge.get("api/decks/" + term)
console.log(response)
}
render () {
return (<div className='ui container'>
<SearchBar onSubmit={this.onSearchSubmit} />
</div>)
}
}
export default App
keyforge.js - this one works!
import axios from 'axios'
const proxyurl = 'https://cors-anywhere.herokuapp.com/'
const url = 'https://www.keyforgegame.com/'
export default axios.create({
// baseURL: 'https://www.keyforgegame.com/api/decks/'
baseURL: proxyurl + url
})
localhost.js - this one does not work
import axios from 'axios'
const proxyurl = 'https://cors-anywhere.herokuapp.com/'
const url = 'http://127.0.0.1:8000/'
export default axios.create({
baseURL: proxyurl + url
})
Error message:
GET https://cors-anywhere.herokuapp.com/http://127.0.0.1:8000/api/cards/b361d7e2-6873-4890-8f87-702d9c89c5ad 404 (Not Found)
Uncaught (in promise) Error: Request failed with status code 404
at createError (createError.js:17)
at settle (settle.js:19)
at XMLHttpRequest.handleLoad (xhr.js:78)
On my computer - http://127.0.0.1:8000/api/cards/b361d7e2-6873-4890-8f87-702d9c89c5ad
takes me to the Django api page for that specifc element. If I get rid of the cors-anywhere url
I get this error -
Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/cards/b361d7e2-6873-4890-8f87-702d9c89c5ad' from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have this cors-anywhere
url prepended to it to solve the No Access-Control-Allow-Origin
error that you see when I hit this to the public api. Since I get the same error when I hit my own private api, I am using the same solution (e.g. the cors-anywhere
url prepeneded to my url.
Thoughts?