gpt4 book ai didi

mysql - 使用 axios 和 express 处理 GET 请求

转载 作者:太空宇宙 更新时间:2023-11-03 11:21:30 24 4
gpt4 key购买 nike

我真的很新手。我使用 bootstrap 创建了一个简单的表单。

My Form with two textboxes for first and last name and a submit button and a reset button

我创建了一个 MySQL 数据库。我在端口 3001 上设置了一个快速服务器,并且能够成功地将我的表单数据发布到数据库。

现在我正尝试通过表单发送 id 并获取详细信息。有人可以指导我完成这个吗?我查看了互联网,但还没有找到一个明确的例子。

提前致谢

我的 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;

我的 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)
})
})

Final Form (with a text field for id and a search button)

最佳答案

在react app的package.json中添加express host“代理”:“http://localhost:3001/”

应用程序.js

//GET Request

handleOnSearch() {
axios.get(`/${this.state.id}`
})
.then(res => {
console.log(this.state.persons);
this.setState({ persons: res.data });
});
}

服务器.js

app.get('/:id', (req, res) => {
const id = req.params.id;
//Rest of the code

})




编辑
你可以用你的旧代码试试这个

app.js 添加 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

})

关于mysql - 使用 axios 和 express 处理 GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59368348/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com