简体   繁体   中英

How to fetch data from an api in React Native from Django rest framework using axios

This is the context Provider That has my state that is fetched from the rest framework api.

import axios from 'axios';

export const PostContext = createContext();

const PostContextProvider = (props) => {

    const [ posts, setPosts ] = useState([]);

    useEffect(() => {
        axios.get('http://127.0.0.1:8000/api/products/')
            .then(res => {
                setPosts(res.data)
            })
            .catch(err => {
                console.log(err);
            })
    }, []);


 return(

    <PostContext.Provider value={{ posts }}>
        {props.children}
    </PostContext.Provider>
  
  )
}


export default PostContextProvider**

When I try to console log it I get an this error in my emulator console.log

 Unrecognized event: {"type":"client_log","level":"log","data":["[]"]}
Array []

When I check my browser, I got this error.

DevTools failed to load SourceMap: Could not load content for http://127.0.0.1:8000/static/rest_framework/css/bootstrap.min.css.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE

I tried to configure my backend using cors headers and the code looks like this

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'corsheaders',
    'django_filters',
    # 'rest_framework_filters',
    'shop.apps.ShopConfig',
    'cart.apps.CartConfig',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]



 CORS_ORIGIN_ALLOW_ALL = True
    
    # CORS_ORIGIN_WHITELIST = (
    #     'http://localhost:19002/'
    # )

if you haven't created any static files ( js or css ) in your django repo then comment out

'django.contrib.staticfiles',

or in setting STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

gussing this after showing your error. This might help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM