Home >Web Front-end >JS Tutorial >How to Pass FormData to a Service in Angular Using Axios?
Problem:
In an Angular application, you have a form that needs to be submitted to a service using Axios, and you want to set the _boundary header to the value of the form's _boundary property. However, you are unable to access the form data from within the Axios instance.
Solution:
By default, Axios automatically sets the Content-Type header for certain request body formats, including FormData. When you pass a FormData instance as the request body, Axios will automatically set the Content-Type header to multipart/form-data and handle mime boundary tokens for you.
Here are the steps to follow in your code:
<code class="js">//component.js const form = new FormData(); form.append('email', '[email protected]') form.append('password', '12121212') dispatch(FetchLogin.action(form))</code>
<code class="js">//loginService.js import api from '@/Services' export default async form => { const response = await api.post('user/login/', form) return response.data }</code>
<code class="js">//Services/index.js import axios from 'axios' import { Config } from '@/Config' const instance = axios.create({ baseURL: Config.API_URL, }) instance.post('fetch-login', { form })</code>
By passing the form object as the form property in the request body payload, Axios will automatically handle the Content-Type header and set it to multipart/form-data with the appropriate mime boundary tokens. You will not need to access the form._boundary property directly.
The above is the detailed content of How to Pass FormData to a Service in Angular Using Axios?. For more information, please follow other related articles on the PHP Chinese website!