Home >Web Front-end >JS Tutorial >How to Pass Data to Services in Axios with FormData?

How to Pass Data to Services in Axios with FormData?

DDD
DDDOriginal
2024-11-04 04:48:02764browse

How to Pass Data to Services in Axios with FormData?

Passing Data to Services in Axios

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>

Handling FormData in Node.js

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>

Conclusion

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn