When transmitting data from a browser, Axios automatically handles certain request body formats and sets appropriate Content-Type headers. If you want to send data as multipart/form-data and manually configure the Content-Type header, you can do so by passing a FormData instance as the request body. Axios will automatically set the header to multipart/form-data; boundary=${form._boundary}.
<code class="javascript">import axios from 'axios'; const form = new FormData(); form.append('email', 'user@example.com'); form.append('password', 'secretpassword'); axios.post('user/login', form) .then((response) => { // Handle response }) .catch((error) => { // Handle error });</code>
When using Axios in Node.js, it doesn't automatically infer Content-Type headers from FormData instances. To work around this, you can use a request interceptor.
<code class="javascript">axios.interceptors.request.use((config) => { if (config.data instanceof FormData) { Object.assign(config.headers, config.data.getHeaders()); } return config; }, null, { synchronous: true });</code>
Or, you can manually merge in the headers when making a request.
<code class="javascript">axios.post('user/login', body, { headers: { 'X-Any-Other-Headers': 'value', ...body.getHeaders(), }, });</code>
In conclusion, by using FormData instances and configuring the request options appropriately, you can pass data from loginService.js to Services/index.js and handle multipart/form-data requests seamlessly.
The above is the detailed content of How to Pass Data to Services in Axios with FormData?. For more information, please follow other related articles on the PHP Chinese website!