I am building a React and Node app and I am trying to send data from React to Node and print it in console. Here is my code:
React code:
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;
Node code:
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}`);
});
I am getting this 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
What am I doing wrong ? I have tried diferent stuff that I googled but none work. It seems that it manages to do the request from React but it doesnt send the value. Why doesn
t it send the value ?
CodePudding user response:
Oddly enough, Node doesn't automatically make req.body
available. You have to manually add a middleware to parse incoming data from the browser, and construct req.body
which can then be used. For years, the body-parser
module was used, now Express 4.16 can do that directly with app.use(express.json());
Some interesting read about that : https://medium.com/@mmajdanski/express-body-parser-and-why-may-not-need-it-335803cd048c