使用来自React Modal的输入修改Axios请求

svmlkihl  于 2022-11-23  发布在  iOS
关注(0)|答案(1)|浏览(134)

我正在创建一个React web应用,它会在每个POST请求上显示一个模态,要求用户添加一个批准令牌。在将请求发送到服务器之前,这个批准令牌会被添加到请求头中。
我使用axios来提出如下请求:

axios({ 
 url: '/backend/call',
 method: 'POST'
})

我通过axios拦截器拦截请求,在这里显示模态。模态有一个文本框和一个提交按钮。

axios.interceptors.request.use(function (config) {
    if (config.method === 'POST') {
        ApprovalPopup.useApprovalPopup.showPopup(); // This displays the modal which has text field and Submit button
        const token = --------; // How do I get the token from the Modal here, after submit is clicked.
        config.headers.approvalToken =  token;
    }
    return config;
 });

参考模态代码:

export type IApprovalPopup = {
    showPopup: () => void;
};

const ApprovalPopupContext = createContext<IApprovalPopup>({
    showPopup: () => undefined,
});

export default function ApprovalPopupProvider({children}: { children: ReactNode }) {
    const dialogRef = useRef<HTMLDialogElement>(null);
    const [ticketID, setTickedID] = useState('');

    function handleSubmit() {
        // update state and make backend call
    }

    function showPopup() {
        dialogRef.current?.show()
    }

    return (
        <ApprovalPopupContext.Provider
            value={{
                showPopup
            }}
        >
                <span slot="body">
                    <div className="ticket-entry">
                        <Label> Ticket ID</Label>
                        <TextField onTextFieldChange={(event) => handleTicketIDEntry(event.detail.value)}
                                         label="Ticket-ID"
                                         value={ticketID}>
                        </TextField>
                    </div>
                    <div className="submit-section">
                        <div className="button">
                            <Button className="button" onClick={handleSubmit}>
                                Submit
                            </Button>
                        </div>
                    </div>
                </span>
            {children}
        </ApprovalPopupContext.Provider>
    );
}

ApprovalPopupProvider.useApprovalPopup = () => useContext(ApprovalPopupContext);

如何从Modal获取令牌并在调用服务器之前将其附加到标头中?

  • 从技术上讲,我可以让第一个调用失败,并将配置传递给Modal。然后Modal会将头附加到配置并进行所需的调用。但在这种情况下,我如何确保响应返回到实际的调用组件。调用组件正在更新本地状态对象/处理自定义错误等,所以它需要解决承诺 *
j5fpnvbx

j5fpnvbx1#

我认为对于您的情况,最好在handleSubmit函数中设置axios头
只需添加以下内容:

function handleSubmit() {
   axios.defaults.headers.common['approvalToken'] = token;
    // update state and make backend call
}

相关问题