首页 > 解决方案 > 在 React 中为 axios 编写 POST 调用

问题描述

我对 JavaScript 的技能很少。

我需要打电话

curl -X POST -H "Content-Type: application/json" -u john.doe:moqui -d "{\"firstName\":\"Hung\", \"lastName\":\"Duong Danh\"}" http://localhost:8080/rest/s1/mantle/parties/person

(卷曲成功。)

在反应代码中

import React, {useRef, useState} from 'react';
import {Toast} from 'primereact/toast';
import {Messages} from 'primereact/messages';
import {Message} from 'primereact/message';
import {InputText} from 'primereact/inputtext';
import {Button} from 'primereact/button';
import axios from "axios";
import {getTokenCookie} from "../TokenCookie";

export const AddCustomer = () => {
    const [username, setUsername] = useState('');
    const [email, setEmail] = useState('');
    const toast = useRef();
    const message = useRef();

    const addSuccessMessage = () => {
        message.current.show({severity: 'success', content: 'Message Detail'});
    };

    const addInfoMessage = () => {
        message.current.show({severity: 'info', content: 'Message Detail'});
    };

    const addWarnMessage = () => {
        message.current.show({severity: 'warn', content: 'Message Detail'});
    };

    const addErrorMessage = () => {
        message.current.show({severity: 'error', content: 'Message Detail'});
    };

    const showSuccess = () => {
        // save.
        axios.post('/http://localhost:8080/rest/s1/mantle/parties/person',
            {
                firstName: 'Hung',
                lastName: 'Duong Danh'
            }, {headers: {moquiSessionToken: getTokenCookie()}})
            .then(function (response) {
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            });
        // return axios.get('http://localhost:8080/rest/s1/mantle/InvoiceFindView',{},{headers:{moquiSessionToken:getTokenCookie()}})
        //     .then(res => res.data);
        toast.current.show({severity: 'success', summary: 'Thông báo', detail: 'Thêm mới khách hàng thành công', life: 3000});
    };

    const showInfo = () => {
        toast.current.show({severity: 'info', summary: 'Info Message', detail: 'Message Detail', life: 3000});
    };

    const showWarn = () => {
        toast.current.show({severity: 'warn', summary: 'Warn Message', detail: 'Message Detail', life: 3000});
    };

    const showError = () => {
        toast.current.show({severity: 'error', summary: 'Error Message', detail: 'Message Detail', life: 3000});
    };

    return (
        <div className="p-grid messages-demo">
            <div className="p-col-12 p-lg-8">
                <div className="card">
                    <h5>Thêm mới khách hàng</h5>
                    <div className="p-field p-grid p-align-start">
                        <label htmlFor="username1" className="p-col-fixed">Tên khách hàng</label>
                        <div className="p-col">
                            <InputText id="username1" value={username} onChange={(e) => setUsername(e.target.value)} required className="p-invalid"></InputText>
                            <Message severity="error" text="Cần nhập vào Tên khách hàng"/>
                        </div>
                    </div>
                    {/*<div className="p-field p-grid">*/}
                    {/*    <label htmlFor="email" className="p-col-fixed">Email</label>*/}
                    {/*    <div className="p-col">*/}
                    {/*        <InputText id="email" value={email} onChange={(e) => setEmail(e.target.value)} required className="p-invalid"></InputText>*/}
                    {/*        <Message severity="error" />*/}
                    {/*    </div>*/}
                    {/*</div>*/}
                    <div className="p-field p-grid">
                        <Toast ref={toast}/>
                        <div className="p-col">
                            <Button type="button" onClick={showSuccess} label="Lưu" className="p-button-success p-mr-2"/>
                        </div>
                    </div>
                </div>
            </div>


        </div>
    );
}

我在这里有问题

const showSuccess = () => {
    // save.
    axios.post('/http://localhost:8080/rest/s1/mantle/parties/person',
        {
            headers: {
                moquiSessionToken: getTokenCookie()
            }
        },
        {
            firstName: 'Hung',
            lastName: 'Duong Danh'
        }
    )
        .then(function (response) {
            console.log(response);
        })
        .catch(function (error) {
            console.log(error);
        });
    // return axios.get('http://localhost:8080/rest/s1/mantle/InvoiceFindView',{},{headers:{moquiSessionToken:getTokenCookie()}})
    //     .then(res => res.data);
    toast.current.show({severity: 'success', summary: 'Thông báo', detail: 'Thêm mới khách hàng thành công', life: 3000});
};

但不是成功。请指导我修复它。

在此处输入图像描述

标签: javascriptreactjsaxios

解决方案


问题在这里:

axios.post('/http://localhost:8080/rest/s1/mantle/parties/person',

/在开头添加了一个并删除了域部分。将其更改为:

const showSuccess = () => {
    // save.
    axios.post('rest/s1/mantle/parties/person',

        {
            firstName: 'Hung',
            lastName: 'Duong Danh'
        },
        {
            headers: {
                moquiSessionToken: getTokenCookie()
            }
        },
    )
        .then(function (response) {
            console.log(response);
        })
        .catch(function (error) {
            console.log(error);
        });
    toast.current.show({severity: 'success', summary: 'Thông báo', detail: 'Thêm mới khách hàng thành công', life: 3000});
};

推荐阅读