繁体   English   中英

为什么我的帖子请求在 POSTMAN 中有效,但在我的反应应用程序中无效?

[英]Why is my post request working in POSTMAN but not in my react application?

下面是我的 POSTMAN 标头以及我用来发送POST的设置。 只有当我将Content-Type更改为appplication/json时它才会起作用。

设置 更多设置

这是我的 web 应用服务器端。

const express = require("express");
const bodyParser = require('body-parser');
const app = express();
const cors = require("cors");
const pool = require("./db");

//middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }))

//POST
app.post("/species", async (req, res) => {
  try {

      console.log(req.body)     
      const {name, description, img} = req.body
      const newSpecies = await pool.query("INSERT INTO speciesdata (name, description, img ) VALUES ($1, $2, $3) RETURNING *",
      [name, description, img]
      );

    console.log(newSpecies)
    res.json(newSpecies.rows);

  } catch (err) {
    console.error(err.message);
  }
});

app.get('/species', async (req, res) => {
  try {
    const allspecies = await pool.query("SELECT * FROM speciesdata");
    res.json(allspecies.rows);

  } catch (err) {
    console.log(err.message)
  }
})

//DELETE
app.delete("/species/:id", async (req, res) => {
  try {

    const {id} = req.params
    const deletespecies = await pool.query("DELETE FROM speciesdata WHERE id = $1",[id]);
    res.json(deletespecies.rows);

  } catch (err) {
    console.error(err.message);
  }
});

app.listen(5000, () => {
  console.log("server has started on port 5000")
})

我的其他请求,例如app.getapp.delete有效。 只有第一个app.post不起作用。 使用 POSTMAN 时, req.body返回我{ name: 'name', description: 'description', img: 'img' } ,我可以看到它显示在我的 web 应用程序上,这正是我想要的。

但是,在我的前端应用程序端,提交表单后,前端和后端都没有显示任何内容。 这是我的反应客户端。

function AddSpeciesForm() {

  const [Nameinput, setName] = useState('');
  const [Descriptioninput, setDescription] = useState('');
  const [imageinput, setImage] = useState('');

  const onSubmitForm = async e => {
    e.preventDefault();
    try {

      const response = await fetch("http://localhost:5000/species", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
           "name" : Nameinput,
           "description": Descriptioninput,
           "img": imageinput
        })
      });
      
      console.log(response)
    } catch (err) {
      console.error(err.message);
    }
  };
  return (
    <AddSpeciesContainer>
      <AddSpeciesWrapper>
        <AddSpeciesform>
          <AddSpeciesH1>Add new species</AddSpeciesH1>
            <InputWrapper>
              <NameInput
                placeholder="Name"
                type="text"
                value={Nameinput}
                onChange={e => setName(e.target.value)}
              />
              <DescriptionInput
                placeholder="Description"
                type="text"
                value={Descriptioninput}
                onChange={e => setDescription(e.target.value)}/>
              <ImgInput
                placeholder="Image"
                type="text"
                value={imageinput}
                onChange={e => setImage(e.target.value)}/>
            </InputWrapper>
          <AddButton onSubmit= {onSubmitForm}>Add</AddButton>
        </AddSpeciesform>
      </AddSpeciesWrapper>
    </AddSpeciesContainer>
  )
}

export default AddSpeciesForm

上次我问这个问题时,我能够解决 POSTMAN 方面的问题,但现在在我的应用程序方面,即使我更改了Content-Type: application/JSON它仍然无法正常工作。 在过去的几天里,我一直在为此苦苦挣扎,非常感谢一些帮助。

我认为 fetch 调用中唯一缺少的参数是 header 部分。

您可以执行以下操作 -

  const addDevice = async (device) => {
  const { hostname: location } = window.location;
  const settings = {
    method: 'POST',
    body: JSON.stringify(device),
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    }
  }

  const response = await fetch(`http://${location}:9000/api/sensors/`, settings);
  if (!response.ok) throw Error(response.message);

  try {
    const data = await response.json();
    return data;
  } catch (err) {
    throw err;
  }
};

有关更多信息,请阅读此答案 - Proper Way to Make API Fetch 'POST' with Async/Await

暂无
暂无

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

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