簡體   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