axios post method errors react

Viewed 111

Im trying to send data using axios post method but keep receiving error 415.

I tried switching to "'Content-Type': application/x-www-form-urlencoded" but still same problem.

Getting data with axios.get works without an error.

What am i doing wrong?

File in which i store API endpoints:

import axios from "axios";

const api = () => {
  const baseUrl = "https://localhost:5001/api";
  let optionAxios = {
    headers: {
      "Content-Type": "text/plain;charset=utf-8",
    },
  };

  return {
    getSubjects: () => axios.get(`${baseUrl}/subjectcontroller/getsubjects`),
    addSubject: (subjectName) =>
      axios.post(
        `${baseUrl}/subjectcontroller/createsubject`,
        {
          name: subjectName,
        },
        optionAxios
      ),
  };
};

export const apiService = api();

Component from which i send data:

import Context from "../../store/context";
import FormContainer from "../UI/FormContainer";
import { apiService } from "../../services/api/api.service";
import { useContext, useRef } from "react";

const AddSubject = () => {
  const ctx = useContext(Context);
  const subject = useRef("");

  const sendData = (e) => {
    e.preventDefault();

    apiService.addSubject(subject.current.value);
  };

  return (
    <FormContainer show={ctx.subjectForm} send={sendData}>
      <label htmlFor="subject">Subject Name: </label>
      <input type="text" id="subject" ref={subject} />
      <button type="submit">Add</button>
    </FormContainer>
  );
};

console logs

1 Answers

If your API expects a JSON body, you have to set the Content-Type headers as "application/json"

  const optionAxios = {
    headers: {
       'Content-Type': 'application/json',
    },
  };
Related