Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

230
Vistas
ClientSide code and server side code proplem

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

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar

0

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')
});
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda