skip to Main Content

I am new in Django and React Native.

Im using Django rest framework to connect my front end to backend. and I am using

"axios"

in sending request to django

I am trying send URL in django. After receiving, the django will give the length of the url as a response to the react native.

I access the path of django in my browser and I think it works fine

enter image description here

However, the react native shows "[AxiosError: Network Error]". Your help is deeply appreacited.

React Native

It sends URL to django

  const [countChar, setcountChar] = useState()

  const sendData = async() =>{

      const url = "Hello"
      
        const response = await axios.post(
          'http://127.0.0.1:8000/validationServer/validate/',
          { url }
        );

        setcountChar(response.data.character_count);
        console.log(countChar)
        
  }

 <TouchableOpacity
              style={{backgroundColor:"white" ,padding:20}}
              onPress={ () => sendData()}>

                 <Text>Send</Text>
  </TouchableOpacity>

validationServer/ view.py


from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializer import UrlSerializer

@api_view(['POST'])
def validation (request):

    if request.method == 'POST':
        serializer = UrlSerializer(data=request.data)
        if serializer.is_valid():
            url = serializer.validated_data['url']
            character_count = len(url)
            return Response({'character_count': character_count})
        return Response(serializer.errors, status=400)

validationServer/ serializer.py

from rest_framework import serializers

class UrlSerializer(serializers.Serializer):
    url = serializers.CharField(max_length=2048)  

validationServer /urls.py

from django.urls import path
from . import views

urlpatterns = [

    path ("validate/",views.validation, name='url-character')
]

// main / urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path("admin/", admin.site.urls),
    path('api-auth/', include('rest_framework.urls')),
    path("validationServer/", include('validationServer.urls'))
]

//setting.py



ALLOWED_HOSTS = [
"127.0.0.1"
    ]

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "validationServer",
     "corsheaders",
    'rest_framework',
    
]

MIDDLEWARE = [
    "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",

        "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware",

]

2

Answers


  1. Your backend looks fine, the way you are sending the request payload is where the issue is. Change this:

    const response = await axios.post(
          'http://127.0.0.1:8000/validationServer/validate/',
          { url }
        );
    

    To:

    const response = await axios.post(
              'http://127.0.0.1:8000/validationServer/validate/',
              { url: url }
            );
        
    
    Login or Signup to reply.
  2. Try to write your question here in more detail, copy the error that React shows, do not shorten or cut off the text, it is important to see the entire text of the error

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search