2021年4月25日星期日

how to create a axios post request using react hooks with a backend framework like django

I have the following React codes using hooks and axios.

I am trying to create a post request to "http://127.0.0.1:8000/api/products/create/" endpoint below.

Unfortunately, I keep getting 405 (Method Not Allowed) as a response when I press the button submit

ProductCreate.js

function CompanyCreate() {    const [fields, handleFieldChange] = FormFields({      name: "",      email: "",    });      function handleSubmit(e) {        e.preventDefault();        console.log("submitted", fields);          let axiosConfig = {          headers: {              'content-type': 'application/json',          }        };          axios.post("http://127.0.0.1:8000/api/products/create/", fields, axiosConfig)        .then(response => {          console.log("Status", response.status);          console.log("Data", response.data);        }).catch((error => {            console.log("error", error);        }));    }  

backend

views

@api_view(["POST"])  def product_create(request):      if request.method == "POST":          serializer = ProductSerializer(data=request.data)          if serializer.is_valid():              serializer.save()              return Response(serializer.data, status=status.HTTP_201_CREATED)          return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)    

urls

path("products/create/", views.product_create, name="create_product"),  

settings

CORS_ORIGIN_ALLOW_ALL=True    CORS_ORIGIN_WHITELIST = (      'http://localhost:3000',      'http://localhost:8000',  )  

I am not sure why its not working, any help would be appreciated.

https://stackoverflow.com/questions/67259596/how-to-create-a-axios-post-request-using-react-hooks-with-a-backend-framework-li April 26, 2021 at 08:47AM

没有评论:

发表评论