How to Write a Hello Node App with ReactJS
How to Write a Hello Node App with ReactJS
1. Create a ReactJS App.
npx create-react-app hello-app
cd hello-app
npm start
2. Create a Backend NodeJS file structure.
Inside your `hello-react` project create a folder backend/server.js
server.js
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.get('/hello', (req, res) => {
res.setHeader('Content-Type', 'text/plain');
res.send('Hello, world!\n');
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
App.js
import React, { useState } from 'react';
function App() {
const [message, setMessage] = useState('');
const handleClick = () => {
var url = 'http://localhost:5000/hello';
fetch(url)
.then(response => response.text())
.then(data => setMessage(data))
.catch(error => console.error('Error:', error));
};
return (
<div className="App">
<button onClick={handleClick}>Get Message</button>
<h1>{message}</h1>
</div>
);
}
export default App;
Install Dependency:
npm install express
npm install cors
Run your Application:
npm start
Output:
Comments
Post a Comment