【问题标题】:Why is my post request working in POSTMAN but not in my react application?为什么我的 post 请求在 POSTMAN 中有效,但在我的 react 应用程序中无效?
【发布时间】:2021-08-19 05:20:40
【问题描述】:

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

这是我的网络应用服务器端。

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,它仍然无法正常工作。过去几天我一直在为此苦苦挣扎,非常感谢您的帮助。

【问题讨论】:

  • Content-type 标头值应为 application/json(全部小写)。你会注意到它在 Postman 中是正确的
  • 我已经改了,但还是没有得到任何东西
  • 您的浏览器控制台报告了任何错误?确保检查 Network 面板并检查请求
  • 浏览器控制台中没有报告。不确定我是否检查正确,但在提交表单后,我的 url 更改为 http://localhost:3000/? 并检查网络面板,status code304 Not Modifiedcontent type : text/html
  • 天哪,谢谢!我已将其更改为 onClick 并且有效。愚蠢的我!谢谢

标签: javascript node.js json postgresql express


【解决方案1】:

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

您可以执行以下操作 -

  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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-31
    • 2021-11-12
    • 2017-09-14
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多