简体   繁体   English

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

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

I'm trying to create my first Web API, I wrote backend in C# and front in react js.我正在尝试创建我的第一个 Web API,我在 C# 中编写了后端,并在反应 js 中编写了前端。

When I'm trying to add a new person in the database through the site, I get an error [object Object] .当我试图通过站点在数据库中添加一个新人时,我收到一个错误[object Object]

But when I'm trying to add a new person in the database through Postman, I got an "Added successfully" message.但是当我试图通过 Postman 在数据库中添加一个新人时,我收到了“添加成功”的消息。

This is my js file这是我的 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>
        )
    }
}

And this is POST handler in the C# file:这是 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");
}

What I meant is this:我的意思是这样的:

  • Properly parametrize your SQL query - never ever concatenate together your SQL statement and the values to send to the server!正确参数化您的 SQL 查询 -永远不要将您的 SQL 语句和要发送到服务器的值连接在一起! SQL Injection Alert ! SQL 注射警报!

  • You don't need a DataTable , nor a SqlDataReader - just use .ExecuteNonQuery() and you're done您不需要DataTableSqlDataReader - 只需使用.ExecuteNonQuery()即可

  • Your INSERT statement should really explicitly list the names of the columns you're inserting into - generally accepted Best Practice - just do it您的INSERT语句应该真正明确地列出您要插入的列的名称 - 普遍接受的最佳实践 - 只需执行此操作

Try this code:试试这个代码:

[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.

相关问题 我正在尝试从React中的对象(API)提取数据 - I'm trying to extract Data from Object (API) in React 尝试获取getDefinitions时出现Wordnik“尝试获取非对象的属性”错误 - Wordnik “Trying to get property of non-object” Error when trying getDefinitions 获取 django.db.utils.OperationalError:子选择返回 11 列 - 尝试将 object 添加到 m2m 字段时预期为 1 - Getting django.db.utils.OperationalError: sub-select returns 11 columns - expected 1 when trying to add an object to a m2m field 当我尝试将 JSON 作为 Object 返回时,我收到“提取类型响应时出错”。 我该如何解决这个问题? - I'm recieving "Error while extracting response for type" when I try to return the JSON as an Object. How can I solve this? 我应该使用发布或放置来编辑数据库中的人员,又应该使用哪个添加新人员? - Should I use Post or Put to edit a person in a database and which should I use to add a new person? 尝试将新问题发布到GitHub存储库时出现错误“ 400错误的请求” - I get error “400 Bad request” when trying to post a new issue into a GitHub repository 我有一个对象,但错误提示我正在对非对象进行函数调用 - I have an object, but error says I'm making a function call on a non-object 试图获取非对象错误 PHP curl 的属性 - Trying to get property of non-object error PHP curl 我正在尝试将以下脚本添加到网站的头部,但它给了我 404 错误 - I'm trying to add the following scripts to the head of a website but it gives me 404 error 我正在尝试获取访问令牌 - I'm trying to get the access token
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM