I run my backend smoothly at first, but since the axios won’t to retrieve GET data from backend, i change the port to 8000 in index.js file, and then the backend server continuously crashed.
This is my index.js as server
import express from 'express' import mysql2 from 'mysql2' import cors from 'cors' const app = express() const db = mysql2.createConnection({ host: 'localhost', user: 'luthfi', password: 'luthfi@MYSQL', database: 'mastercrm', port: '8000' }) app.use(express.json()); app.use(cors()); app.get("/", (req, res) => { res.json('This is representative the json response success') }) app.get("/data/contacts", (req, res) => { const q = 'SELECT * FROM contacts' db.query(q, (err, data) => { if(err) return res.json(err) return res.json(data) }) }) app.get("/data/leads", (req, res) => { const q = 'SELECT * FROM leads' db.query(q, (err, data) => { if(err) return res.json(err) return res.json(data) }) }) app.post("/data/contacts", (req, res) => { const q = 'INSERT INTO contacts (`person`, `person_address`, `institution`, `position`, `institution_address`, `email_address`, `email_address2`, `phone`, `phone2`, `socmed_link`, `status`, `descriptions`) VALUES (?)' const values = [ req.body.person, req.body.person_address, req.body.institution, req.body.position, req.body.institution_address, req.body.email_address, req.body.email_address2, req.body.phone, req.body.phone2, req.body.socmed_link, req.body.status, req.body.descriptions ]; db.query(q, [values], (err, data) => { if(err) return res.json(err) return res.json('Insert Data Dari Backend Berhasil') }) }) app.post("/data/leads", (req, res) => { const q = 'INSERT INTO leads (`invoice_date`, `lead_title`, `sales_name`, `person`, `institution`, `descriptions`, `trade_value`, `lead_stage`, `lead_status`, `notes`, `deal_date`) VALUES (?)' const values = [ '2024-05-04', 'Penjualan IFP', 'Dany', 'Harry Tanoe', 'SoundEye Production', '1 unit IFP Maxhub V6 ViewPro', 126900000, 'Baru', 'Unqualified', 'Percobaan insert data dari backend', '2024-05-04' ]; db.query(q, [values], (err, data) => { if(err) return res.json(err) return res.json('Insert Data Dari Backend Berhasil') }) }) app.listen(3000, () => { console.log('Berhasil terkoneksi ke backend!') })
Also axios can’t GET data, it shows cannot GET / in the browser. I try to switching each other between backend and frontend port but didn’t work
This is my frontend:
import React from "react";
import { useEffect, useState } from "react";
import axios from 'axios';
const Dashboard = () => {
const [contacts, setContacts] = useState([])
useEffect(() => {
const fetchAllContacts = async () => {
try {
const res = await axios.get('http://localhost:3000/data/contacts')
console.log(res)
} catch (err) {
console.log(err)
}
}
fetchAllContacts()
}, [])
return(
<div>Dashboard</div>
)
}
export default Dashboard