“Cannot GET /” when trying to connect to localhost:4000/addProduct in node.js

Issue

I am working with node.js as backend server. When requesting to "localhost:4000/addProduct" I got the error "Cannot GET /addProduct" in the browser but when I request to "localhost:4000" it is showing the output ‘Mobile Fair’ and I do not know what is the matter. My code is as follows:

const express = require('express')
const app = express()
require('dotenv').config()

const MongoClient = require('mongodb').MongoClient;
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.ywjyr.mongodb.net/${process.env.DB_NAME}?retryWrites=true&w=majority`;
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(err => {
  const collection = client.db(process.env.DB_NAME).collection(process.env.DB_COLLECT);
  app.post('/addProduct', (req, res) => {
    const newData = req.body;
    console.log("adding  new product: ",newData);
  })    
  console.log("you got error: ",err)

});

app.get('/', (req, res) => {
    res.send('Mobile Fair')
  })

app.use(function( req, res, next){
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
}); 
app.listen(4000);

My front end code is given below:

import axios from 'axios';
import React, { useState } from 'react';
import { useForm } from 'react-hook-form';
import Admin from '../Admin/Admin';

const AddProduct = () => {
  const [imageUrl, setImageUrl] = useState(null);

  const handleImageUpload = (event) => {
    console.log(event.target.files[0])
    const imageData = new FormData();
    imageData.set('key', 'key');
    imageData.append('image', event.target.files[0]);

    axios.post('uri', imageData)
      .then(function (response) {
        console.log(response);
        setImageUrl(response.data.data.display_url);
      })
      .catch(function (error) {
        console.log(error);
      });

  }

  const { register, handleSubmit, watch, errors } = useForm();
  const onSubmit = data => {
    const newData = {
      name: data.name,
      memory: data.memory,
      price: data.price,
      image: imageUrl
    }
    console.log(newData);
    

    fetch('http://localhost:4000/addProduct', {
      method: 'POST', // or 'PUT'
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(newData),
    })
      .then(res=> console.log("server side response: ",res))
  };
  return (
    <div className="d-flex">
      <div><Admin /></div>
      <div>
        <form onSubmit={handleSubmit(onSubmit)}>
          <input name="name" placeholder="Enter Name" ref={register({ required: true })} />
          {errors.name && <span>This field is required</span>}
          <input name="memory" placeholder="Enter Memory" ref={register({ required: true })} />
          {errors.memory && <span>This field is required</span>}<br></br>
          <input name="price" placeholder="Enter Price" ref={register({ required: true })} />
          {errors.memory && <span>This field is required</span>}
          <input name="image" type="file" onChange={handleImageUpload} /><br />
          <input type="submit" value="Save" />
        </form>
      </div>
    </div>
  );
};

export default AddProduct;

Solution

Try this.

fetch(' "localhost:4000/addProduct"', {
  method: 'post',
  headers: {
    'Accept': 'application/json, text/plain, */*',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(newData)
}).then(res => res.json())
  .then(res => console.log(res));

Also in order to handle json data you need to parse it. add this line after your

const app = express()
app.use(express.json());

Update : just take your entire app.post code and paste it below that app.get code snippet,remove it from your client.connect callback.

app.get('/', (req, res) => {
    res.send('Mobile Fair')
})

app.post('/addProduct', (req, res) => {
    const newData = req.body;
    console.log("adding  new product: ",newData);
  })    
  console.log("you got error: ",err)

Answered By – Jatin Mehrotra

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published