0. Background
Since none of my knowledge has anything to do with backend, I've been searching up how to connect Node.js to React.js for a quite long time.. (maybe being lazy took most of it tho). Anyway, I am making notes of how the connection has been made in this project.
1. Download
Downloading is the easiest part.
npm install express
npm install mysql
I wasn't sure cors is required but most of exmaples that I've found include using cors. In the case to use it, download it as well with this command line.
npm install cors
It doesn't matter that you download them in the server difectory or in the very top directory (if there is no server directory, make it.).
2. Creating Files
1. Create config directory under server directory
2. Create db.js under the config directory
3. Create index.js and package.json under server directory
3. Writing db.js
In db.js file, mysql will be connected. The final code is like this:
const mysql = require('mysql');
const db = mysql.createConnection({
host: "localhost",
user : "root",
password: "1234",
database:"rate_my_residents"
});
db.connect(function(err){
if(err) throw err;
console.log("Connected!");
});
module.exports = db;
Database will be connected with "Connected!" message on the console once the server gets connected.
* I got an error, ER_NOT_SUPPORTED_AUTH_MODE when I tried to connect it. If you see this error later when you do, go to mysql, the directory where you downloaded it, and use this query.
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '1234';
4. Writing index.js
This file is basically the spot of connection and interaction between server and client.
const express = require("express");
const db = require('./config/db');
const PORT = process.env.PORT || 3001;
const app = express();
app.get("/", (req, res) => {
res.json({ message: "Hello from server!" });
});
app.post("/post", (req,res)=>{
console.log("Connected to React");
res.redirect("/");
});
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});
});
Port number can be anything but the same one as client. It can be 3001, 5000, 8080, etc.
In the line 8, "/" means route path that React Loute has made.
When you go to http://localhost:3001, you can see the json file { message: "Hello from server:"}.
When you connect server, the message 'Server listening on 3001' will be visible on the command line.
With the further codes that will be added in React.js, it will produce the message "Connected to React".
5. Add a form in App.js
To interact between server and React.js, some more codes are needed.
import './App.css';
import React from 'react';
import Main from './pages/Main';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
function App() {
return (
<>
<BrowserRouter>
<Routes>
<Route path="/" element={<Main />} />
</Routes>
</BrowserRouter>
<form action="../../post" method="post"
className="form">
<button type="submit">Connected?</button>
</form>
</>
);
}
export default App;
The form is a button that will be in the React.js page.
6. Add some in package.json file
6-1. Proxy in package.json in the client side
To wrap up our journey, this line should be added in package.json file of the React.js:
"proxy": "http://localhost:3001"
If your port number used for server is 5000, the line should be also "proxy": "http://localhost:5000".
6-2. Start scripts in package.json file in the server side
{
"scripts":
{ "start": "node server/index.js"}
}
Whatever there is in your file, just add "start": "node server/index.js"
6-3. Dependencies in package.json file in the server side
For mysql, you should add it into dependencies in the server-side package.json file.
"dependencies": { "mysql": "^2.18.1" }
My version of mysql is 2.18.1. You should check it since it can be different from mine and put it there like that.
7. How to check if it works
You need 2 terminals. In the one, go to the server directory, and type node index.js. In the other one, fo to the client directory, and type whatever you use to run React.js. For me, it is npm run start.
8. Result
Once you type node index.js, you should be able to see this on the command line in the server-side terminal.
Server listening on 'your port number'
Connected!
And when you run React.js, you will see this botton.
And when you click it, "Connected to React" will be popped up on the command line.
'Project > Rate My Resident' 카테고리의 다른 글
5. Query Callback (쿼리콜백) in Node.js (0) | 2023.04.11 |
---|---|
4. Using Variables in useEffect (useEffect에서 변수 쓰기) (0) | 2023.03.16 |
3. Spread Operator (Managing Array State) (0) | 2023.03.02 |
1. How to put props to a page with enter key (엔터키 눌렀을 때 페이지로 인자 넘겨주기) (0) | 2022.12.31 |
0. Motivation / Folder Structure (0) | 2022.12.24 |