简体   繁体   English

axios 发布方法错误反应

[英]axios post method errors react

Im trying to send data using axios post method but keep receiving error 415.我正在尝试使用 axios post 方法发送数据,但一直收到错误 415。

I tried switching to "'Content-Type': application/x-www-form-urlencoded" but still same problem.我尝试切换到“'Content-Type':application/x-www-form-urlencoded”,但仍然是同样的问题。

Getting data with axios.get works without an error.使用 axios.get 获取数据没有错误。

What am i doing wrong?我究竟做错了什么?

File in which i store API endpoints:我存储 API 端点的文件:

 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控制台日志

If your API expects a JSON body, you have to set the Content-Type headers as "application/json"如果您的 API 需要 JSON 主体,则必须将Content-Type标头设置为“application/json”

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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