繁体   English   中英

当我试图添加一个新人时,我得到一个错误 [Object object]

[英]I get an error [Object object] when Î'm trying to add a new person

我正在尝试创建我的第一个 Web API,我在 C# 中编写了后端,并在反应 js 中编写了前端。

当我试图通过站点在数据库中添加一个新人时,我收到一个错误[object Object]

但是当我试图通过 Postman 在数据库中添加一个新人时,我收到了“添加成功”的消息。

这是我的 js 文件

import React,{Component} from 'react';
import {Modal,Button, Row, Col, Form} from 'react-bootstrap';

export class AddDepModal extends Component{
    constructor(props){
        super(props);
        this.handleSubmit=this.handleSubmit.bind(this);
    }

    handleSubmit(event){
        event.preventDefault();
        fetch(process.env.REACT_APP_API+'department',{
            method:'POST',
            headers:{
                'Accept':'application/json',
                'Content-Type':'application/json'
            },
            body:JSON.stringify({
                borzhnuka_id:null,
                borzh_name:event.target.borzh_name.value
            })
        })
        .then(res=>res.json())
        .then((result)=>{
            alert(result);
        },
        (error)=>{
            alert('Failed');
        })
    }
    render(){
        return (
            <div className="container">

<Modal
{...this.props}
size="lg"

aria-labelledby="contained-modal-title-vcenter"
centered
>
    <Modal.Header clooseButton>
        <Modal.Title id="contained-modal-title-vcenter">
            Додати
        </Modal.Title>
    </Modal.Header>
    <Modal.Body>

        <Row>
            <Col sm={6}>
                <Form onSubmit={this.handleSubmit}>
                    <Form.Group controlId="borzh_name">
                        <Form.Label>Ім'я</Form.Label>
                        <Form.Control type="text" name="borzh_name" required 
                        placeholder="borzh_name"/>
                    </Form.Group>

                    <Form.Group controlId="borzh_last_name">
                        <Form.Label>Прізвище</Form.Label>
                        <Form.Control type="text" name="borzh_last_name" required 
                        placeholder="borzh_last_name"/>
                    </Form.Group>

                    <Form.Group controlId="amount">
                        <Form.Label>Amount</Form.Label>
                        <Form.Control type="int" name="amount" required 
                        placeholder="amount"/>
                    </Form.Group>
                    
                    <Form.Group controlId="Date_of_offer">
                        <Form.Label>Дата приєднання</Form.Label>
                        <Form.Control 
                        type="date"
                        name="Date_of_offer"
                        required
                        placeholder="Date_of_offer"
                        />
                       
                        
                    </Form.Group>
                    <Form.Group>
                        <Button variant="primary" type="submit">
                            Додати
                        </Button>
                    </Form.Group>
                </Form>
            </Col>
        </Row>
    </Modal.Body>
    
    <Modal.Footer>
        <Button variant="danger" onClick={this.props.onHide}>Close</Button>
    </Modal.Footer>
</Modal>
            </div>
        )
    }
}

这是 C# 文件中的 POST 处理程序:

[HttpPost]
public JsonResult Post(Department dep)
{
    string query = @"insert into dbo.All_borzh values
                     ('" + dep.borzhnuka_id + @"',
                     '" + dep.borzh_name + @"',
                     '" + dep.borzh_last_name + @"',
                     '" + dep.amount + @"',
                     '" + dep.Date_of_offer + @"')
                     ";

    DataTable table = new DataTable();
    string sqlDataSource = _configuration.GetConnectionString("EmployeeAppCon");
    SqlDataReader myReader;

    using (SqlConnection myCon = new SqlConnection(sqlDataSource))
    {
        myCon.Open();

        using (SqlCommand myCommand = new SqlCommand(query, myCon))
        {
            myReader = myCommand.ExecuteReader();
            table.Load(myReader); ;
            myReader.Close();
            myCon.Close();
        }
    }

    return new JsonResult("Added successfully");
}

我的意思是这样的:

  • 正确参数化您的 SQL 查询 -永远不要将您的 SQL 语句和要发送到服务器的值连接在一起! SQL 注射警报!

  • 您不需要DataTableSqlDataReader - 只需使用.ExecuteNonQuery()即可

  • 您的INSERT语句应该真正明确地列出您要插入的列的名称 - 普遍接受的最佳实践 - 只需执行此操作

试试这个代码:

[HttpPost]
public JsonResult Post(Department dep)
{
    // properly **parametrize** your query! 
    string query = @"INSERT INTO dbo.All_borzh(list-of-columns-here) 
                     VALUES (@Id, @Name, @LastName, @Amount, @DateOfOffer);";
    
    string connectionString = _configuration.GetConnectionString("EmployeeAppCon");
    
    // setup connection and command
    using (SqlConnection myCon = new SqlConnection(connectionString))
    using (SqlCommand myCmd = new SqlCommand(query, myCon))
    {
        // add parameters and values
        myCmd.Parameters.Add("@Id", SqlDbType.Int).Value = dep.borzhnuka_id;
        // Here, I'm just *guessing* what those datatypes and string lengths are - adapt as needed!
        myCmd.Parameters.Add("@Name", SqlDbType.VarChar, 100).Value = dep.borzh_name;
        myCmd.Parameters.Add("@LastName", SqlDbType.VarChar, 100).Value = dep.borzh_last_name;
        myCmd.Parameters.Add("@Amount", SqlDbType.Decimal, 20, 4).Value = dep.amount;
        myCmd.Parameters.Add("@DateOfOffer", SqlDbType.Date).Value = dep.Date_of_offer;
        
        // open connection, execute query, close connection
        myCon.Open();
        
        int numberOfRowsInserted = myCmd.ExecuteNonQuery();
        
        myCon.Close();
    }

    return new JsonResult("Added successfully");
}

暂无
暂无

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

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