【问题标题】:React Application form cannot POST to my backend apiReact 应用程序表单无法 POST 到我的后端 api
【发布时间】:2021-12-30 20:07:58
【问题描述】:

我已经通过 Postman 和 Insomnia 创建了一个带有 node 和 express 的后端 api,效果很好,但由于某种原因,我的 create 函数不会发布到我的 api。它可以很好地登录到 API,并且每个用户输入的字段都会返回表单,但问题与 axios.post 之后的某个地方有关,好像我输入了不正确的 url 它会抛出 404,但如果我输入正确url 它不会抛出任何错误,而是完全跳过 .then(response 函数并直接进入 console.log(3)。任何与此相关的想法或帮助都会很棒,谢谢!

进口

import {useState} from 'react'
import axios from 'axios'
import {TextField, MenuItem, FormControl, Select, InputLabel, Button, Checkbox} from '@mui/material'
import { useNavigate } from 'react-router-dom'

提交表单代码

const submitForm = () => {
        console.log(form)

        let token = localStorage.getItem('token')
        console.log(1)

        axios.post('http://localhost:9000/miniatures/create', form,{
            headers: {
                "Content-Type": "application/json",
                "Authorization": `jwt ${token}`
            }
        })
                .then(response => {
            console.log(2)
            console.log(response.data)
            navigate(`/miniatures/${response.data._id}`)
        })
        .catch(err => console.log(err))
        console.log(3)
    }

【问题讨论】:

    标签: node.js reactjs mongodb express


    【解决方案1】:

    React 可能不知道如何proxy API requests to the Express server

    package.json为前端,尝试添加:

      "proxy": "http://localhost:9000",
    

    然后,将您的post 请求发送到(类似)axios.post(/miniatures/create)。确切的路径将取决于您如何构建 Express 路线。可能类似于/api/miniatures/create

    在开发中,开发服务器会识别出它不是 静态资产,并将代理您的请求。

    【讨论】:

    • 不幸的是,事实并非如此。如果我这样做,它认为 /miniatures 是前端。如果我保持原样但给出错误的 url,它会显示 404,但如果我得到正确的 url,它什么也没说,所以我真的不确定发生了什么。
    • 你能从 Express 发布你的路线吗?
    猜你喜欢
    • 2019-10-22
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    • 2019-12-16
    • 2020-07-08
    • 2020-08-08
    • 1970-01-01
    相关资源
    最近更新 更多