简体   繁体   English

Axios.post 返回发送 null 即使后端正在工作

[英]Axios.post returns send null even though backend is working

I am making an application where a user can make an Order for Kebab.我正在制作一个应用程序,用户可以在其中订购烤肉串。

However when i'm using Axios.post some of the values always return null (Kebab and Drink).但是,当我使用 Axios.post 时,某些值总是返回 null(烤肉串和饮料)。

When i'm using postman it all works as expected though, so it must be something with the frontend, I reckon.当我使用 postman 时,它一切都按预期工作,所以它一定是前端的东西,我想。

This is my orderForm component:这是我的 orderForm 组件:

export const OrderForm = (props: OrderFormProps) => {

    const [kebabChoice, setKebabChoice] = useState<KebabDto[]>();
    const [drinkChoice, setDrinkChoice] = useState<DrinkDto[]>();
    
    useEffect(()=>{
        axios.get(`https://localhost:7117/api/Kebab`)
        .then((response: AxiosResponse<KebabDto[]>) =>{
            setKebabChoice(response.data);

        })
    },[])
    useEffect(()=>{
        axios.get(`https://localhost:7117/api/Drink`)
        .then((response: AxiosResponse<DrinkDto[]>) =>{
            setDrinkChoice(response.data);

        })
    },[])

    return(
        <Formik
            initialValues = {props.model}
            onSubmit = {props.onSubmit}
            validationSchema = {Yup.object({
                firstName: Yup.string().required('This field is required').firstLetterUppercase()
            })}
        >
            {(formikProps) =>(
                <Form>
                    
                <TextField displayName="Firstname" field="firstName" type="text"/>
                <TextField displayName="Lastname" field="lastName" type="text" />
                <TextField displayName="Employee number" field="empNr" type="number" />
                
                <SelectField displayName="Kebab" field="typeOfKebab"  optionLabel="Välj kebab">
                        <>
                            {kebabChoice?.map(kebabs => 
                                <option key={kebabs.id} value={kebabs.name}>{kebabs.name}</option>)}
                        </>  
                </SelectField>
                <SelectField displayName="drink" field="typeOfDrink"  optionLabel="Välj Dricka">
                        <>
                            {drinkChoice?.map(drinks => 
                                <option key={drinks.id} value={drinks.typeOfDrink}>{drinks.typeOfDrink}</option>)}
                        </>  
                </SelectField>

                <Button className="btn btn-primary" disabled={formikProps.isSubmitting} type="submit">Save Changes</Button>
                <Link className="btn btn-secondary mt-2" to="/drinks">Cancel</Link>
                </Form>
            )}
        </Formik>
    )
}

interface OrderFormProps{
    model: OrderDto;
    onSubmit(values: OrderDto, actions: FormikHelpers<OrderDto>) : void;
}

Here i am also fetching the different kinds of kebabs and drinks that the user can choose from.在这里,我还获取用户可以选择的不同种类的烤肉串和饮料。

Here is the component where I'm trying to create the order:这是我尝试创建订单的组件:

export const CreateOrder = () => {

    const history = useHistory()

    const  CreateNewOrder = async (order: OrderDto) =>{
        try {
            await axios.post('https://localhost:7117/api/Order', order);
            console.log(order)
            history.push("/orders");
    
        } catch (error) {
            console.error(error);
        }
    }

    return(


        <>
            <h3>Create Order</h3>

            <OrderForm model={{firstName: '', lastName: '', empNr: 0}}
                onSubmit={values => 
                    CreateNewOrder(values)
                    // console.log(values)
                }
            />

        </>
    )
}

It takes one argument where the order is a type of OrderDto:它需要一个参数,其中订单是一种 OrderDto:

export interface OrderDto{
    firstName: string;
    lastName: string;
    empNr?: number;
    kebab?: KebabDto;
    drink?:DrinkDto;
}

So when im creating a pizza, i get the values in my backend from firstName, lastName and empNr.因此,当我创建披萨时,我在后端从 firstName、lastName 和 empNr 获取值。 Though Kebab and Drink is always null no matter what I do, except if im using Postman.尽管无论我做什么,烤肉串和饮料总是 null,除非我使用 Postman。

Postman body: Postman 正文:

{
  "firstName": "Marcus",
  "lastName": "Rosberg",
  "empNr": 1111,
  "kebab": {
    "name": "Kebabrulle"
  },
  "drink": {
    "typeOfDrink": "Fanta"
  }
}

.net backend: .net 后端:

EndPoint:

[HttpPost]
        public async Task<ActionResult> PostOrder([FromBody] OrderCreationDto orderCreation)
        {

            
            var order = mapper.Map<Order>(orderCreation);

            context.Orders.Add(order);
            //await context.SaveChangesAsync();

            return NoContent();
        }

OrderCreationDto:
 public class OrderCreationDto
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int EmpNr { get; set; }
        public KebabCreationDto Kebab { get; set; }
        public DrinkCreationDto Drink { get; set; }
    }

KebabCreationDto:

 public class KebabCreationDto
    {
        public string Name { get; set; }
    }

DrinkCreationDto:

 public class DrinkCreationDto
    {
        public string TypeOfDrink { get; set; }

    }

This is the code im currently using for my orders.这是我目前用于我的订单的代码。 I made a relationship between Order => kebab and Order => Drink where and order is supposed to have one Drink and one kebab.我在 Order => kebab 和 Order => Drink 之间建立了关系,并且订单应该有一份饮料和一份烤肉串。

In my form in react im fetching Kebab and Drinks and use these in an option so that i can use whats already in the database and put it in my order.在我的反应表单中,我正在获取烤肉串和饮料,并在一个选项中使用它们,这样我就可以使用数据库中已有的内容并将其放入我的订单中。 Atleast thats how it is supposed to work.至少这就是它应该如何工作的。

Your drink and kebab fields are labeled typeOfDrink and typeOfKebab I cant see that you do any processing of these values and the api expects.你的饮料和烤肉串字段被标记为typeOfDrinktypeOfKebab我看不到你对这些值和 api 期望的进行任何处理。 kebab and drink fields. kebabdrink领域。

If you only need to pass the drink/kebab type to the api and the api can resolve the drink/kebab that should be fine and you should just update the api and the interface to only take those fields.如果您只需要将饮料/烤肉串类型传递给 api 并且 api 可以解析应该没问题的饮料/烤肉串,您应该只更新 api 和界面以仅采用这些字段。 However if you need more meta data from Drink-/KebabDto you will need to accommodate that in the frontend.但是,如果您需要来自 Drink-/KebabDto 的更多元数据,则需要在前端提供这些数据。 Either by making sure the that data is set in the form or resolve it from the type before passing it to the backend.通过确保在表单中设置该数据或在将其传递到后端之前从类型中解析它。

EDIT:编辑:

With the updated answer you can see that the for will not give you the same object as you pass with postman.使用更新后的答案,您可以看到 for 不会给您提供与 postman 相同的 object。

You will have to change the filed to accommodate the type you expect in the api: field="typeOfKebab" => field="kebab.name" and field="typeOfDrink" => field="drink.typeOfDrink"您必须更改文件以适应您在 api 中期望的类型:field="typeOfKebab" => field="kebab.name" and field="typeOfDrink" => field="drink.typeOfDrink"

<SelectField displayName="Kebab" field="kebab.name"  optionLabel="Välj kebab">
<SelectField displayName="drink" field="drink.typeOfDrink"  optionLabel="Välj Dricka">

However since you only use one field in both KebabDto and DrinkDto, why not just change OrderDto to但是,由于您只在 KebabDto 和 DrinkDto 中使用一个字段,为什么不将 OrderDto 更改为

export interface OrderDto{
    firstName: string;
    lastName: string;
    empNr?: number;
    kebab?: string;
    drink?: string;
}

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

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