Home > Back-end >  ClientSide code and server side code proplem
ClientSide code and server side code proplem

Time:01-12

i had a proplem with making two js files one to be put in 'website' directory and the other outside it and when i add a post request it adds a new item to the array from the server side js file and itried it alot and it didnt work so .. thats My ServerSide Code

/* Empty JS object to act as endpoint for all routes */
projectData = {};

/* Express to run server and routes */
const express = require('express');

/* Start up an instance of app */
const app = express();

/* Dependencies */
const bodyParser = require('body-parser')
/* Middleware*/
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const cors = require('cors');
app.use(cors());

/* Initialize the main project folder*/
app.use(express.static('website'));

const port = 3000;
/* Spin up the server*/
const server = app.listen(port, listening);
 function listening(){
    // console.log(server);
    console.log(`running on localhost: ${port}`);
  };

// GET route
app.post('/add', function (req, res) {
    let data = req.body;
    console.log(data);
});


// POST an animal
const data = []

app.post('/animal', addAnimal)

function addAnimal (req,res){
    data.push(req.body);
    console.log(data);
}


and That Is My ClientSide Code

/* Function to POST data */
const postData = async ( url = '', data = {})=>{
    console.log(data)
      const response = await fetch(url, {
      method: 'POST', // *GET, POST, PUT, DELETE, etc.
      credentials: 'same-origin', // include, *same-origin, omit
      headers: {
          'Content-Type': 'application/json',
      },
      body: JSON.stringify(data), // body data type must match "Content-Type" header        
    });
  
      try {
        const newData = await response.json();
        console.log(newData);
        return newData
      }catch(error) {
      console.log("error", error);
      // appropriately handle the error
      }
  }
  
  // TODO-Call Function
  postData('/addAnimal', {animal:'Tiger'});
  postData('/addAnimal',  {animal:'Lion'});

when i run the code inside the vs code editor it displays "{ animal: 'lion' } { animal: 'Tiger' }"

But it never console log the data

CodePudding user response:

you forget to send the respone must the route callback have a res endpoint

function addAnimal (req,res){
    data.push(req.body);
    console.log(data);
    // add res end point 
    res.json({msg : 'added'})
}
//here too
app.post('/add', function (req, res) {
    let data = req.body;
    console.log(data);
    res.end('hello world')
});

CodePudding user response:

Your route is /add or /animal not /addAnimal

postData('/add', {animal:'Tiger'});

in your ServerSide this function should display a log

app.post('/add', function (req, res) {
    let data = req.body;
    console.log(data);
});

You can't console.log the data in your try / catch because you don't return any response in your server side. But first try log data in your server side controller for confirm the good serverSide execution, and return your response.

  •  Tags:  
  • Related