简体   繁体   English

使用 axios 和 express 处理 GET 请求

[英]Handling GET request with axios and express

I am really new to react.我真的很新来反应。 I created a simple form with bootstrap.我用引导程序创建了一个简单的表单。

我的表单有两个文本框,分别是名字和姓氏,还有一个提交按钮和一个重置按钮

I created a MySQL database.我创建了一个 MySQL 数据库。 I set up an express server on port 3001 and was able to post my form data to the database successfully.我在端口 3001 上设置了一个快速服务器,并且能够成功地将我的表单数据发布到数据库。

Now I am trying to send an id through the form and get the details.现在我正在尝试通过表单发送一个id并获取详细信息。 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:我的 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:我的 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)
    })
})

最终表格(带有 id 文本字段和搜索按钮)

Add the express host in package.json of react app "proxy": "http://localhost:3001/"在react app "proxy": "http://localhost:3001/" package.json中添加express主机"proxy": "http://localhost:3001/"

app.js应用程序.js

//GET Request

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

server.js服务器.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()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服务器.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
}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM