Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

249
Views
Envío de datos desde React a Node backend

Estoy creando una aplicación React and Node y estoy tratando de enviar datos de React a Node e imprimirlos en la consola. Aquí está mi código:

Código de reacción:

 import React, { Component } from 'react'; import axios from 'axios'; class Test extends React.Component { constructor(props) { super(props); this.state = { name: 'Serban' }; this.tick = this.tick.bind(this); } tick() { console.log(this.state.name); const article = { n: this.state.name }; axios.post('http://localhost:3001/api', article) } componentDidMount() { // Simple POST request with a JSON body using axios } render() { return( <div> <button onClick={this.tick}>Send</button> </div> ); } } export default Test;

Código de nodo:

 const express = require("express"); const router = express.Router(); const axios = require('axios'); const cors = require("cors"); const PORT = process.env.PORT || 3001; const app = express(); app.use(cors()) app.post('/api', function(req, res) { var nume = req.body.n; console.log("Salut " + nume); }); app.listen(PORT, () => { console.log(`Server listening on ${PORT}`); });

Estoy recibiendo este error:

 Server listening on 3001 TypeError: Cannot read property 'n' of undefined at C:\react-efactura\server\index.js:16:23 at Layer.handle [as handle_request] (C:\react- efactura\node_modules\express\lib\router\layer.js:95:5) at next (C:\react-efactura\node_modules\express\lib\router\route.js:137:13) at Route.dispatch (C:\react-efactura\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (C:\react- efactura\node_modules\express\lib\router\layer.js:95:5) at C:\react-efactura\node_modules\express\lib\router\index.js:281:22 at Function.process_params (C:\react- efactura\node_modules\express\lib\router\index.js:335:12) at next (C:\react-efactura\node_modules\express\lib\router\index.js:275:10) at cors (C:\react-efactura\node_modules\cors\lib\index.js:188:7) at C:\react-efactura\node_modules\cors\lib\index.js:224:17

Qué estoy haciendo mal ? He intentado diferentes cosas que busqué en Google pero ninguna funciona. Parece que logra hacer la solicitud de React pero no t send the value. Why doesn envía el valor?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Por extraño que parezca, Node no hace que req.body esté disponible automáticamente. Debe agregar manualmente un middleware para analizar los datos entrantes del navegador y construir req.body que luego se puede usar. Durante años, se usó el módulo body-parser , ahora Express 4.16+ puede hacerlo directamente con app.use(express.json());

Algunas lecturas interesantes sobre eso: https://medium.com/@mmajdanski/express-body-parser-and-why-may-not-need-it-335803cd048c

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!