Hello i was worked on crud app everything is worked fine but when i create delete route i cannot post data to server i get empty string and error cannot get if i follow get link i try to comment all delete methods but still no one is working even toast are stopped working works only navigate buttons ..
Server
index.js
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const mysql = require("mysql");
const cors = require("cors");
var db = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "crud_contact",
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/api/get", function(req,res){
console.log('Hello');
db.query('SELECT * FROM contact_db', function (error, result) {
res.send(result);
});
});
app.post("/api/post", (req, res) => {
const {name, email, contact} = req.body;
const sqlInsert =
`INSERT INTO contact_db (name,email, contact)
VALUES (?, ?, ?)`;
db.query(sqlInsert, [name, email, contact], (error,result) => {
res.send(result);
if(error) {
console.log(error);
}
});
})
// app.delete("/api/remove/:id", (req, res) => {
// const {id} = req.params;
// const sqlRemove =
// `DElETE FROM contact_db WHERE id = ?`;
// db.query(sqlRemove, id , (error,result) => {
// if(error) {
// console.log(error);
// }
// });
// })
//
app.get("/", (req, res) => {
// app.listen(5000, () => {
// con.connect(function(err) {
// if (err) throw err;
// console.log("Connected!");
// var sql = `INSERT INTO contact_db(name,email, contact)
// VALUES('popas','berazumis#gmail.com',8585858)`;
// con.query(sql, function (err, result) {
// if (err) throw err;
// console.log("record inserted");
// });
// });
// });
});
app.listen(5000, () => {
console.log("Listening port 5000");
});
Client
Add edit user
AddEdit.js
import React, { useState, useEffect } from "react";
import { useNavigate, useParams, Link } from "react-router-dom";
import "./AddEdit.css";
import axios from "axios";
import { toast } from "react-toastify";
const initiaState = {
name: "",
email: "",
contact: "",
};
const AddEdit = () => {
const [state, setState] = useState(initiaState);
const { name, email, contact } = state;
const navigate = useNavigate();
const handleSubmit = (e) => {
e.preventDefault();
if (!name || !email || !contact) {
toast.error("Please fill all labels below");
} else {
axios
.post("http://localhost:5000/api/post", {
name,
email,
contact
})
.then(() => {
setState({ name: "", email: "", contact: "" });
})
.catch((err) => toast.error(err.response.data));
setTimeout(() => navigate.push("/"), 500);
}
};
const handleInputChange = (e) => {
const { name, value } = e.target;
setState({ ...state, [name]: value });
};
return (
<div style={{ marginTop: "100px" }}>
<form
style={{
margin: "auto",
padding: "15px",
maxWidth: "400px",
alignContent: "cener",
}}
onSubmit={handleSubmit}
>
<label htmlFor="name">Name</label>
<input
type="text"
id="name"
name="name"
placeholder="Type Name..."
value={name}
onChange={handleInputChange}
/>
<label htmlFor="email">Email</label>
<input
type="email"
id="email"
name="email"
placeholder="Type Email..."
value={email}
onChange={handleInputChange}
/>
<label htmlFor="contact">Contact</label>
<input
type="number"
id="contact"
name="contact"
placeholder="Type contact number"
value={contact}
onChange={handleInputChange}
/>
<Link to="/">
<input type="submit" value="save" />
<input type="button" value="Go Back" />
</Link>
</form>
</div>
);
};
export default AddEdit;
Home.js
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import "./Home.css";
import { toast } from "react-toastify";
import axios from "axios";
const Home = () => {
const [data, setData] = useState([]);
const loadData = async () => {
const response = await axios.get("http://localhost:5000/api/get");
setData(response.data);
};
useEffect(() => {
loadData();
}, []);
/* const deleteContact = (id) => {
if(window.confirm("Are you sure that you wanna delete contact")) {
axios.delete(`http://localhost:5000/api/remove/${id}`);
toast.success("Contact Deleted Successfully");
setTimeout(() => loadData(), 500);
}
}
*/
return (
<div style={{ marginTop: "150px" }}>
<Link to="addContact">
<button className="btn btn-contact">Add contact</button>
</Link>
<table className="styled-table">
<thead>
<tr>
<th style={{ textAlign: "center" }}>No.</th>
<th style={{ textAlign: "center" }}>Name</th>
<th style={{ textAlign: "center" }}>Email</th>
<th style={{ textAlign: "center" }}>Contact</th>
<th style={{ textAlign: "center" }}>Action</th>
</tr>
</thead>
<tbody>
{data.map((item, index) => {
return (
<tr key={item.id}>
<th scope="row">{index + 1}</th>
<td>{item.name}</td>
<td>{item.email}</td>
<td>{item.contact}</td>
<td>
<Link to={`/update/${item.id}`}>
<button className="btn btn-edit" >Edit</button>
</Link>
<button className="btn btn-delete" /*onClick={() => deleteContact}*/ >Delete</button>
<Link to={`/view/${item.id}`}>
<button className="btn btn-view">View</button>
</Link>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
};
export default Home;
When you create a app.delete route, you no longer use POST method on your client side, you need to use the DELETE method.
Client Side Example
const res = await axios.delete('https://example.com/delete', { data: { answer: 42 } });
Server Side Example
app.delete('/delete', async(req, res,next) => {
console.log('req.body', req.body)
//prints { data: { answer: 42 } }
})
Related
I've been trying to figure this out for hours, but i think im doing it wrong. So what im basically doing is.
-> Fetch the specific user, and throw it into the placeholder -> which is working
but when I try to edit the information and then when i try to save it this error shows and then in my phpadmin, it saves a null. it seems that I can't connect the front and the backend.
sql: 'UPDATE users SET name = NULL, email = NULL, mobile = NULL WHERE id = ${id} '
Edit.jsx
import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
const EditUser = () => {
const navigate = useNavigate()
const [data, setData] = useState([])
const [inputs, setInputs] = useState([])
const { id } = useParams()
useEffect(() => {
const getUser = async () => {
const res = await axios.get(`http://localhost:5000/${id}`)
setData(res.data[0])
}
getUser()
}, [])
const handleSubmit = async () => {
try {
await axios.put(`http://localhost:5000/${id}`, inputs)
} catch (error) {
console.log(error)
}
}
const handleChange = (e) => {
setInputs({ ...inputs, [e.target.name]: e.target.value })
}
return (
<div>
<form
action=""
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'column',
}}
onSubmit={handleSubmit}
>
<label htmlFor="">Name</label>
<input type="text" placeholder={data.name} onChange={handleChange} />
<label htmlFor="">Email</label>
<input type="text" placeholder={data.email} onChange={handleChange} />
<label htmlFor="">Mobile</label>
<input type="text" placeholder={data.mobile} onChange={handleChange} />
<button type="submit">save</button>
</form>
</div>
)
}
export default EditUser
backend.js
app.put('/:id', (req, res) => {
const id = req.params.id
const name = req.body.name
const email = req.body.email
const mobile = req.body.mobile
pool.query(
`UPDATE users SET name = ?, email = ?, mobile = ? WHERE id = ${id} `,
[name, email, mobile],
(err, result) => {
if (err) {
console.log(err)
} else {
res.send(result)
}
}
)
})
app.get('/:id', (req, res) => {
const { name, email, mobile } = req.body
const { id } = req.params
pool.query(`SELECT * FROM users WHERE id = ${id} `, (err, result) => {
if (err) {
console.log(err)
} else {
res.send(result)
}
})
})
May be you should try :
The following states :
const EditUser = () => {
const navigate = useNavigate()
const [data, setData] = useState([])
const [name, setName] = useState("")
const [email, setEmail] = useState("")
const [mobile, setMobile] = useState("")
const { id } = useParams()
For your request :
const handleSubmit = async () => {
let datas ={
name: name,
email: email,
mobile: mobile
}
try {
await axios.put('http://localhost:5000/updateUser/'+id, datas)
} catch (error) {
console.log(error)
}
}
Then you just update your states that way :
<form
action=""
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'column',
}}
onSubmit={handleSubmit}
>
<label htmlFor="">Name</label>
<input type="text" placeholder={data.name} onChange={()=>
{setName(e.currentTarget.value)} />
<label htmlFor="">Email</label>
<input type="text" placeholder={data.email} onChange={()=>
{setEmail(e.currentTarget.value)} />
<label htmlFor="">Mobile</label>
<input type="text" placeholder={data.mobile} onChange={()=>
{setMobile(e.currentTarget.value)} />
<button type="submit">save</button>
</form>
For you back end maybe you should add some informations in the adress (to avoid confusion with you app.get):
app.put('updateUser/:id', (req, res) => {
const id = req.params.id
const name = req.body.name
const email = req.body.email
const mobile = req.body.mobile
pool.query(
`UPDATE users SET name = ?, email = ?, mobile = ? WHERE id = ${id} `,
[name, email, mobile],
(err, result) => {
if (err) {
console.log(err)
} else {
res.send(result)
}
}
)
})
I hope it will help you !
I think I did it actually, but I dont know if this is the right method. so what i did is
instead of directing submit it as an await
const handleSubmit = async () => {
try {
await axios.put(`http://localhost:5000/${id}`, inputs)
} catch (error) {
console.log(error)
}
}
i did this.
const handleSubmit = async (e) => {
e.preventDefault()
try {
const res = await axios.put(`http://localhost:5000/${id}`, inputs)
setInputs(res.data)
} catch (error) {
console.log(error)
}}
Hey guys, if its wrong, please show me the other way.
My code was working before when my two tables in MySQL were both just "id".
To add more specificity and to be able to add a foreign key, I changed the ids in the two tables to:
bugtracker_table:
id --> project_id
ticket_table:
id --> ticket_id
Now all of the sudden I am getting the error: Uncaught TypeError: projects.map is not a function - on line 25 in Dashboard.js (highlighted below), when before my app worked perfectly.
Dashboard.js
import React, { useState, useEffect } from "react";
import { DataTable } from "primereact/datatable";
import { Column } from "primereact/column";
import { Button } from "primereact/button";
// import ButtonDemo from './ButtonDemo';
import { Chart } from "primereact/chart";
import { InputText } from "primereact/inputtext";
import { InputTextarea } from "primereact/inputtextarea";
import axios from "axios";
import { useHistory, Link } from "react-router-dom";
import { Dialog } from "primereact/dialog";
// import { Media } from "react-bootstrap/Media"
// import ProjectsTable from "./Tables/ProjectsTable";
// import TicketsPieChart from "./Tables/TicketsPieChart"
// import API from
//project table
//eslint-disable no-unused-vars
const TableDemo = () => {
const [project_name, setProjectName] = useState("");
const [description, setDescription] = useState("");
const [projects, setProjects] = useState([]);
const history = useHistory();
Line 25 const projectsToShow = projects.map(project => {
return {
...project,
project_name: <Link to={`/projects/${project.project_id}`}>{project.project_name}</Link>,
};
});
useEffect(() => {
getProjects();
}, []);
const [displayResponsive, setDisplayResponsive] = useState(false);
const getProjects = async () => {
const response = await axios.get("http://localhost:5002/bugtracker_table");
setProjects(response.data);
};
const saveProject = async (e) => {
e.preventDefault();
await axios.post("http://localhost:5002/bugtracker_table", {
project_name: project_name,
description: description,
});
history.push("/");
};
const dialogFuncMap = {
displayResponsive: setDisplayResponsive,
};
const onClick = (name) => {
dialogFuncMap[`${name}`](true);
};
const onHide = (name) => {
dialogFuncMap[`${name}`](false);
};
const renderFooter = (name) => {
return (
<div>
{" "}
<Button onClick={saveProject} type="submit" label="Submit" className="p-button-rounded p-button-success mr-2 mb-2 success" />
</div>
);
};
// const paginatorLeft = <Button type="button" icon="pi pi-refresh" className="p-button-text" />;
// const paginatorRight = <Button type="button" icon="pi pi-cloud" className="p-button-text" />;
return (
<>
<div className="grid table-demo">
<div className="col-12">
<div className="card">
<h5>Projects</h5>
<div>
<Button className="p-button-rounded mr-2 mb-2 npbutton" label="New Ticket" onClick={() => onClick("displayResponsive")} />
</div>
<Dialog className="dialogModal" header="Create Ticket" visible={displayResponsive} onHide={() => onHide("displayResponsive")} breakpoints={{ "960px": "75vw" }} style={{ width: "35vw" }} footer={renderFooter("displayResponsive")}>
<form>
<h5>Project Name</h5>
<InputText value={project_name} onChange={(e) => setProjectName(e.target.value)} type="text" placeholder="Enter project name"></InputText>
<h5>Project Description</h5>
<InputTextarea value={description} onChange={(e) => setDescription(e.target.value)} type="text" placeholder="Enter project description" autoResize rows="4" cols="40" />
</form>
</Dialog>
{/* // <Link to="/ticketlist" className="col-12"> */}
<div>
{/* // className="card"></Link> */}
<DataTable
// sortMode="single" sortField="representative.name"
editMode="row"
value={projectsToShow}
sortOrder={1}
scrollable
scrollHeight="400px"
responsiveLayout="scroll"
paginator
paginatorTemplate="CurrentPageReport FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown"
currentPageReportTemplate="Showing {first} to {last} of {totalRecords}"
rows={5}
rowsPerPageOptions={[5, 10, 25]}
>
{/* // paginatorLeft={paginatorLeft} paginatorRight={paginatorRight}> */}
<Column field="project_name" header="Project Name" style={{ minWidth: "200px" }}></Column>
<Column field="description" header="Description" style={{ minWidth: "350px" }}></Column>
<Column field="createdAt" header="Created On" style={{ minWidth: "150px" }}></Column>
{projects.map((project, index) => (
<tr key={project.project_id}>
<td>{index + 1}</td>
<td>{project.description}</td>
<td>{project.createdAt}</td>
</tr>
))}
</DataTable>
</div>
</div>
</div>
<div className="grid p-fluid">
<div className="col-12 lg:col-6">
<div className="card flex flex-column align-items-center">
<h5>Tickets by Type</h5>
<Chart type="pie" focus={"type"} />
</div>
</div>
</div>
<div className="grid p-fluid">
<div className="col-12 lg:col-6">
<div className="card flex flex-column align-items-center">
<h5>Tickets by Priority</h5>
<Chart type="pie" focus={"priority"} />
</div>
</div>
</div>
<div className="grid p-fluid">
<div className="col-12 lg:col-6">
<div className="card flex flex-column align-items-center">
<h5>Tickets by Status</h5>
<Chart type="pie" focus={"status"} />
</div>
</div>
</div>
</div>
</>
);
};
export default React.memo(TableDemo);
I figured because I changed the id names in MySQL, I would need to adjust the id names in the backend as well so I tried changing everywhere it said id before, to now project_id but I think I did it incorrectly and believe this is where the error is coming from.
backend/controllers/products.js
import Project from "../models/productModel.js";
export const getAllProjects = async (req, res) => {
try {
const projects = await Project.findAll();
res.json(projects);
} catch (error) {
res.json({ message: error.message });
}
}
export const getProjectsById = async (req, res) => {
try {
const project = await Project.findAll({
where: {
project_id: req.params.id
}
});
res.json(project[0]);
} catch (error) {
res.json({ message: error.message });
}
}
export const createProject = async (req, res) => {
try {
await Project.create(req.body);
res.json({
"message": "Project Created"
});
} catch (error) {
res.json({ message: error.message });
}
}
export const updateProject = async (req, res) => {
try {
await Project.update(req.body, {
where: {
project_id: req.params.id
}
});
res.json({
"message": "Project Updated"
});
} catch (error) {
res.json({ message: error.message });
}
}
export const deleteProject = async (req, res) => {
try {
await Project.destroy({
where: {
project_id: req.params.id
}
});
res.json({
"message": "Project Deleted"
});
} catch (error) {
res.json({ message: error.message });
}
}
backend/routes/index.js
import express from "express";
import { getAllProjects, createProject, getProjectsById, updateProject, deleteProject } from "../controllers/Products.js";
const router = express.Router();
router.get("/", getAllProjects);
router.get("/:project_id", getProjectsById);
router.post("/", createProject);
router.patch("/:project_id", updateProject);
router.delete("/:project_id", deleteProject);
/backend/models/ProductModels.js
import { Sequelize } from "sequelize";
import db from "../config/database.js";
const { DataTypes } = Sequelize;
const Project = db.define('bugtracker_table',{
project_name:{
type: DataTypes.STRING
},
description:{
type: DataTypes.STRING
},
createdAt:{
type: DataTypes.DATE
}
},{
freezeTableName: true
});
export default Project;
backend/database.js
import { Sequelize } from "sequelize";
const db = new Sequelize('bugtracker_db', 'root', '', {
host: "localhost",
dialect: "mysql",
port: 8889,
username: "root",
password: "root",
});
export default db;
Uncaught TypeError: projects.map is not a function means that the variable assigned to projects is not an array, as the map function is only available on arrays.
If you take a look at the response you are getting from http://localhost:5002/bugtracker_table You will almost certainly see that this data is not a array.
In fact you do not have a route which corresponds to /bugtracker_table.
Try changing your routes file like below
router.get("/bugtracker_table", getAllProjects);
router.get("/:project_id", getProjectsById);
router.post("/bugtracker_table", createProject);
router.patch("/:project_id", updateProject);
router.delete("/:project_id", deleteProject);
So now your getAllProjects route matches up to what you are calling in React.
I have an input field in which I am pre populating the value of, with the value from the DB. it is a record that already exists, in which I would like to edit. The input field however, is not letting me edit the field. Please find it below:
import React, { useState, useEffect } from "react";
import axios from "axios";
import { useHistory } from "react-router-dom";
const EditServicesPage = () => {
const history = useHistory()
const [myData, setMyData] = useState({});
const [isLoading, setIsLoading] = useState(false);
const [showEditButton, setShowEditButton] = useState(false);
const [fields, setFields] = useState({
updatedByCNUM: "",
content: "",
site: ""
})
var idFromListServicesPage = history.location.state.id
console.log("22: " + idFromListServicesPage)
useEffect(() => {
axios
.post('/getDocToEdit', {id : idFromListServicesPage})
.then((res) => {
console.log("line 28 esp.js: " + res.data)
setMyData(res.data);
setIsLoading(true);
})
.catch((error) => {
// Handle the errors here
console.log(error);
})
.finally(() => {
setIsLoading(false);
});
}, []);
const deleteById = (id) => {
console.log(id);
axios
.post(`/deleteDoc`, { id: id })
.then(() => {
console.log(id, " worked");
window.location = "/admin/content";
})
.catch((error) => {
// Handle the errors here
console.log(error);
});
};
const handleInputChange = e => setFields(f => ({...f, [e.target.name]: e.target.value}))
const editById = (id, site, content, updatedByCNUM) => {
console.log(id, site, content, updatedByCNUM);
axios
.post(
'/editDoc',
({
id: id,
location: site,
content: content,
updatedByCNUM: updatedByCNUM
})
)
.then(() => {
console.log(id, " worked");
window.location = "/admin/content";
})
.catch((error) => {
console.log(error);
});
};
const onClickEdit = (e, _id) => {
e.preventDefault();
var site = document.getElementById("site").value;
var content = document.getElementById("content").value;
var updatedByCNUM = document.getElementById("updatedByCNUM").value;
console.log(site, content, updatedByCNUM)
editById(_id, site, content, updatedByCNUM);
};
const onTyping = (value) => {
if (value.length > 0) {
setShowEditButton(true);
} else {
setShowEditButton(false);
}
};
return (
<table id="customers">
<h1>Edit Services Page</h1>
<tr>
<th>site</th>
<th>content</th>
<th>updatedByCNUM</th>
<th>Actions</th>
</tr>
<tr>
<td>
<input
// ref={site.ref}
type="text"
value={myData.site}
onInput={(e) => onTyping(e.target.value)}
onChange={handleInputChange}
placeholder={myData.site}
name="site"
id="site"
/>{" "}
{/* <input
type="text"
placeholder={site}
onChange={(e) => onTyping(e.target.value)}
name="site"
id="site"
/> */}
</td>
<td>
<input
// ref={content.ref}
type="text"
value={myData.content}
onInput={(e) => onTyping(e.target.value)}
onChange={handleInputChange}
placeholder={myData.content}
name="content"
id="content"
/>
</td>
<td>
<input
type="text"
placeholder={myData.updatedByCNUM}
name="updatedByupdatedByCNUMhide"
id="updatedByupdatedByCNUMhide"
readOnly
/>{" "}
</td>
<td>
{/* <input type="hidden" placeholder={myData.updatedByCNUM} name="updatedByCNUM" id="updatedByCNUM" value={updatedByCNUM}/>{" "} */}
</td>
<td>
<button
onClick={(e) => {
e.preventDefault();
deleteById(idFromListServicesPage);
}}
disabled={isLoading}
>
Delete
</button>
<button
onClick={(e) => {
e.preventDefault();
editById(idFromListServicesPage);
}}
>
Edit
</button>
{showEditButton && (
<button onClick={(e) => onClickEdit(e, idFromListServicesPage)}>Submit Edit</button>
)}
</td>
</tr>
</table>
);
};
export default EditServicesPage;
showButton:
const onTyping = (value) => {
if (value.length > 0) {
setShowEditButton(true);
} else {
setShowEditButton(false);
}
};
when I try to type into the input field, it doesn't allow me to type, but keeps the pre existing value there already. how can I fix this?
You need a state which has the initial values from the DB
const [data, setData] = useState({
site: newData.site || "",
content: newData.content || "",
});
const handleInputChange = (e) => {
const { name, value } = e.target;
setData((currentData) => ({ ...currentData, [name]: value }));
};
return (
// .....
<input
// ref={site.ref}
type="text"
value={data.site} // use data.site here instead of the newData
onChange={handleInputChange}
placeholder={myData.site}
name="site"
id="site"
/>
// .....
);
Just add setMyData like this:
const onTyping = (name, value) => {
setMyData({ ...myData, [name]: value });
if (value.length > 0) {
setShowEditButton(true);
} else {
setShowEditButton(false);
}
};
And
onInput={(e) => onTyping(e.target.name, e.target.value)}
I am really new to react. I created a simple form with bootstrap.
I created a MySQL database. I set up an express server on port 3001 and was able to post my form data to the database successfully.
Now I am trying to send an id through the form and get the details. Can someone please guide me through this. I looked over the internet but could not find a clear example yet.
Thanks in advance
My app.js:
import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.css";
import "./App.css";
import axios from "axios";
import { Form } from "react-bootstrap";
class App extends Component {
constructor(props) {
super(props);
this.state = {
id: "",
fName: "",
lName: "",
password: "",
email: "",
persons: [],
};
}
handleOnSubmit(event) {
event.preventDefault();
alert("Data Submitted Successfully");
//--------------------------------------------------------------------------------
//POST Request
// const user = {
// fName : this.state.fName,
// lName : this.state.lName,
// // email : this.state.email,
// // password : this.state.password,
// };
// axios.post(`http://localhost:3001`, { user })
// .then(res => {
// console.log(res);
// console.log(res.data);
// })
}
handleOnChange(event) {
let name = event.target.name;
let value = event.target.value;
this.setState({
[name]: value
});
}
//GET Request
handleOnSearch() {
axios.get(`http://localhost:3001`,{
params: {
id: this.state.id
}
})
.then(res => {
console.log(this.state.persons);
this.setState({ persons: res.data });
});
}
render() {
return (
<div>
<Form onSubmit={this.handleOnSubmit.bind(this)}>
<Form.Group controlId="firstName">
<Form.Label>First Name</Form.Label>
<Form.Control
type="text"
placeholder="Enter first name"
name="fName"
onChange={this.handleOnChange.bind(this)}
/>
</Form.Group>
<Form.Group controlId="lastName">
<Form.Label>Last Name</Form.Label>
<Form.Control
type="text"
placeholder="Enter last name"
name="lName"
onChange={this.handleOnChange.bind(this)}
/>
</Form.Group>
<div>
<button
variant="primary"
type="submit"
className="btn btn-primary mx-1"
>
Submit
</button>
<button variant="primary" type="reset" className="btn btn-warning">
Clear
</button>
</div>
<hr />
<br />
<div>
<Form.Group controlId="id">
<Form.Label>Id</Form.Label>
<Form.Control
type="text"
placeholder="Enter id"
name="id"
onChange={this.handleOnChange.bind(this)}
/>
</Form.Group>
<button variant="primary" className="btn btn-warning mx-1" onClick={this.handleOnSearch.bind(this)}>
Search
</button>
</div>
</Form>
</div>
);
}
}
export default App;
my server.js:
// Creating the express app
var express = require('express');
var app = express();
// Getting mysql database access
var mysql = require('mysql');
// Enabling support to the Cross-Origin Resource Sharing protocol
var cors = require('cors');
app.use(cors());
// Extracting the body of the req to expose it on command
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Writing connection details
var con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'reactmysql'
})
// Connecting to the database
con.connect((err) => {
if (err) {
console.log("There was an error connecting to the database: " + err);
}
console.log("Connected to the database");
})
// Starting listening on port 3001
app.listen(3001, () => {
console.log("I am listening on port 3001");
})
// Getting the data from the body whenever user inputs them and assigning them to backend variables
app.post('/', (req, res) => {
// var fName = req.body.user.fName
// var lName = req.body.user.lName
console.log(req);
console.log(res);
// var sql = "INSERT INTO ('firstname', 'lastname') VALUES ('" + fName + "', '" + lName + "')"
var sql = "SELECT * FROM `mytable`";
con.query(sql, (err, result) => {
if (err) {
console.log("There was an error in your query: " + err);
}
console.log("Query Executed Successfully");
console.log(result)
})
})
Add the express host in package.json of react app
"proxy": "http://localhost:3001/"
app.js
//GET Request
handleOnSearch() {
axios.get(`/${this.state.id}`
})
.then(res => {
console.log(this.state.persons);
this.setState({ persons: res.data });
});
}
server.js
app.get('/:id', (req, res) => {
const id = req.params.id;
//Rest of the code
})
edit
You can try this with your old code
In app.js add preventDefault()
handleOnSearch(event) {
event.preventDefault();
axios
.get(`http://localhost:3001`, {
params: {
id: this.state.id,
},
})
.then((res) => {
console.log(this.state.persons);
this.setState({ persons: res.data });
});
}
server.js
app.get('/', (req, res) => {
const id = req.query.id;
//Rest of the code
})
Use this with all handling.
axios.get('/:id', {
params: {
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
// always executed
});
Hi I try to make simple contact from in react, but I stuck on fetch() method.
This is my code. I have no idea what is wrong.
FrontEnd
export default class ContactForm extends React.Component<IContactFormProps, any> {
constructor(props) {
super(props);
// local state
this.state = {
tl: new TimelineMax({paused: true, delay: 1}),
name: "",
email: "",
subject: "",
message: "",
sent: false,
}
this.handleOnSubmit = this.handleOnSubmit.bind(this);
this.handleClearForm = this.handleClearForm.bind(this);
this.handleChange = this.handleChange.bind(this);
this.startAnimation = this.startAnimation.bind(this);
}
handleOnSubmit(e) {
console.log("ContactForm->handleOnSubmit(e).");
e.preventDefault();
let formData = new FormData();
formData.append(name, this.state.name);
console.log("formData: " + formData);
fetch('/contact', {
method: 'POST',
body: formData
})
.then((response) => {
console.log("response: " + response);
console.log("response.ok: " + response.ok);
return response.json();
})
.then((responseJson) => {
console.log("responseJson: " + responseJson);
})
.catch((error) => {
console.log("error from fetch: " + error);
});
}
handleClearForm(e) {
console.log("ContactForm->handleClearForm(e).");
// e.preventDefault();
}
handleChange(event) {
const target = event.target;
const name = event.target.name;
const value = event.target.value;
this.setState({
[name]: value
});
// console.log("event.target.value: " + event.target.value);
// this.setState({value: event.target.value});
}
startAnimation() {
console.log("ContactForm->startAnimation().");
}
componentDidMount() {
this.startAnimation();
}
componentWillUnmount() {
}
render() {
return (
<form className="contact-form-cnt"
onSubmit={ this.handleOnSubmit }>
<div className="top-row">
<input type="text" name="name" placeholder="Name"
className="name" ref="name"
value={this.state.name} onChange={this.handleChange}/>
<input type="text" name="email" placeholder="Em#il"
className="email" ref="email"
value={this.state.email} onChange={this.handleChange}/>
</div>
<input type="text" name="subject" placeholder="Subject"
className="subject" ref="subject"
value={this.state.subject} onChange={this.handleChange}/>
<textarea name="message" placeholder="Write Your message here."
className="message" ref="message"
value={this.state.message} onChange={this.handleChange}></textarea>
<button type="submit" name="submit"
className="submit" ref="Send"
onClick={ this.handleClearForm }>Send</button>
</form>
);
};
};
BackEnd
'use strict';
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const winston = require('winston');
const distPath = path.join(__dirname, '../dist');
const indexFileName = 'index.html';
const app = express();
const PORT = process.env.PORT || 8080;
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.use(express.static(distPath));
app.get('*', (req, res) => res.sendFile(path.join(distPath, indexFileName)));
app.post("/contact", (req, res) => {
try {
console.log("mail sending succes!");
}
catch ( error ) {
console.log("mail sending failure!");
}
});
app.listen(PORT, (err) => {
if (err) {
winston.error(err);
return;
}
winston.info(`Listening on port ${PORT}`);
});
URL:
http://localhost:8080/contact
and error
POST http://localhost:8080/contact 404 (Not Found)
I think it's something with url, but I'am out of ideas. Any sugestions?
try something like this:
app.post("/contact", (req, res) => {
res.json({"foo": "bar"});
});
this way you are setting an json object as result. Let me know if works.