【问题标题】:Successfully POST form data to Express App, use sequelize to insert into MySQL database成功POST表单数据到Express App,使用sequelize插入MySQL数据库
【发布时间】:2020-05-19 16:19:08
【问题描述】:

我目前正在尝试使用 sequelize 将表单数据 (axios) 从反应前端发布到我的 express 应用程序到 mysql 数据库。到目前为止,我可以成功发出 GET 请求并显示到 UI。但是,在设置我的发布请求时,我在控制台中收到 404 错误。我已经读了很多书,当然我很新,有些想法可能就在我头上,但我似乎无法破解为什么我可以成功发出 GET 请求的案例,但是不是发布请求,甚至是到控制台。我也很好奇设置 POST 端点的最佳实践。

到目前为止,这是我的代码:

客户表格

import React, { Component } from 'react'
import axios from 'axios';

export default class AddVisitorForm extends Component {

  constructor(props) {
    super(props)

    this.state = {
       lastName: '',
       firstName: ''
    }
  }


  onChange = (e) => {
    this.setState({ 
      [e.target.name]: e.target.value
     })
  };

  handleSubmit = (e) => {
    event.preventDefault();
    console.log(this.state)
    axios.post('http://localhost:8000/', this.state)
    .then(response => {
      console.log(response)
    })
    .catch(error => {
      console.log(error)
    })
  }


  render() {
    const { lastName, firstName } = this.state
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <label>
            Last Name:
            <input type="text" name="lastName" onChange={this.onChange } value={lastName} />
          </label>
          <label>
            First Name:
            <input type="text" name="firstName" onChange={this.onChange } value={firstName} />
          </label>
          <button type="submit">Add Guest</button>
        </form>
      </div>
    )
  }
};

续集模型

const sequelize = require('../database/sequelize');
const Sequelize = require("sequelize");

module.exports = sequelize.define('actor', {
  lastName: {
    field: 'last_name',
    type: Sequelize.STRING
  },
  firstName: {
    field: 'first_name',
    type: Sequelize.STRING
  },
  }, {
  timestamps: false
});

快递应用

const express = require("express");
const Actor = require('./models/Actor');
const cors = require('cors');

const app = express();

app.use(cors());


app.get('/actor', function(request, response) {
  Actor.findAll().then((actor) => {
    response.json(actor);
  });
});

app.get('/actor/:id', function(request, response) {
  let id = request.params.id;

  Actor.findByPk(id).then((actor) => {
    if (actor) {
      response.json(actor);
    } else {
      response.status(404).send();
    }
  });
});

app.post('/addactor', function(request, response) {
  Actor.create()
}



app.listen(8000);

您会注意到 app.post 函数不完整,因为我不太清楚如何使用表单数据进行设置。我知道这不是世界上最难弄清楚的事情,但我似乎无法在控制台中显示发布请求,也无法在快速应用程序中正确设置发布请求以将数据插入mysql表。如果有人能帮助我重回正轨,我将不胜感激。

【问题讨论】:

    标签: mysql node.js reactjs express sequelize.js


    【解决方案1】:

    您应该回复 POST。 下面是正确的代码。 response.json 写响应请求。 如果你没有明确写响应,表示服务器挂起什么也不做。

    app.post('/addactor', function(request, response) {
      Actor.create().then(createdInstance => {
         response.json(createdInstance)
      })
    }
    

    如果你不想在这个函数中响应,就这样写。

    app.post('/addactor', function(request, response, next) {
      Actor.create()
      next()
    }
    

    next 函数移动到下一个匹配路由。

    如果你只是想成功则响应OK,失败则响应404,写

    app.post('/addactor', function(request, response, next) {
      Actor.create().then(() => {
         response.end()
      }).catch(error => {
         response.status(404).end()
      })
    }
    

    next 函数移动到下一个交配路线。

    请求正文和请求参数可以这样访问

    app.post('/addactor', function(request, response, next) {
      const body = request.body // json body parsed to javascript object {lastName: '', firstName: ''}
      const params = request.params // query parameters parsed to javascript object
      Actor.create(body).then(() => {
         response.end()
      }).catch(error => {
         response.status(404).end()
      })
    }
    

    此代码不安全,因此您应该编写一些过滤器和验证。

    Express Doc

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多