0

Below is my POSTMAN headers as well as the settings I used to send my POST. Only when I changed the Content-Type to appplication/json then it works.

settings more settings

This is my web application server side.

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")
})

My other requests such as the app.get as well as app.delete works. It is only the first one app.post that is not working. When using POSTMAN, the req.body returns me { name: 'name', description: 'description', img: 'img' } and i can see it being displayed on my web application which is what I want.

However, on my frontend application side, upon submitting the form, nothing was being displayed both on the frontend and the backend side. This is my react client side.

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

The previous time I asked this I was able to solve the POSTMAN side but right now on my application side even when I had change the Content-Type: application/JSON it is still not working. I have been strugguling with this for the past few days, would really appreciate some help.

Derrick Tay
  • 53
  • 1
  • 8
  • The `Content-type` header value should be `application/json` (all lowercase). You'll note that it is correct in Postman – Phil Jun 01 '21 at 01:02
  • I have changed it but i still not getting anything – Derrick Tay Jun 01 '21 at 01:19
  • Any errors reported in your browser console? Make sure to check the _Network_ panel and inspect the request – Phil Jun 01 '21 at 01:24
  • No reports in browser console. Not sure if i am checking the right thing but upon submitting the form, my url changes to ```http://localhost:3000/?``` and checking the network panel, the ```status code``` is ```304 Not Modified``` and ```content type : text/html``` – Derrick Tay Jun 01 '21 at 01:29
  • What is `AddButton` and does it even trigger `onSubmit` events? Typically, only a `
    ` triggers a _submit_ event. Also, your `AddSpeciesForm` component appears to be recursive (in that it contains itself). This doesn't seem right given the code you've shown
    – Phil Jun 01 '21 at 01:30
  • 1
    OMG THANK YOU! I have changed it to onClick and it worked. Stupid me! Thankss – Derrick Tay Jun 01 '21 at 01:33

1 Answers1

-1

I think the only missing argument in the fetch call is in the header section.

You can do something like below -

  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;
  }
};

For more information please read this answer - Proper Way to Make API Fetch 'POST' with Async/Await

vikasvmads
  • 542
  • 1
  • 7
  • 12