2

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
  • It's an http status code error from your api? This has nothing to do with react. All of this code is fine. Commented Jun 14, 2022 at 18:14

1 Answer 1

0

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',
    },
  };
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.