在 Axios 中将数据传递给服务 [英] Pass Data to Service in Axios
问题描述
我想在我的标题中设置 _boundry
.
I want to set _boundry
in my header.
首先,我发送表单数据:
First, I dispatch the form data:
//component.js
const form = new FormData();
form.append('email', 'eray@serviceUser.com')
form.append('password', '12121212')
dispatch(FetchLogin.action(form))
其次,我准备api调用;
Second, I prepare api call;
//loginService.js
import api from '@/Services'
export default async form => {
const response = await api.post('user/login/', form)
return response.data
}
第三,我进行api调用;
Third, I make api call;
//Services/index.js
import axios from 'axios'
import { Config } from '@/Config'
const instance = axios.create({
baseURL: Config.API_URL,
headers: {
'Content-Type': `multipart/form-data; boundary=${form._boundary}`, //Cannot access form here
},
timeout: 3000,
})
instance.interceptors.response.use(
response => response,
({ message, response: { data, status } }) => {
return handleError({ message, data, status })
},
)
export default instance
我想访问 axios
instance
中的 form
数据,以便能够在其中使用 form._boundry
标题
.
I want to access form
data within to axios
instance
to be able to use form._boundry
in headers
.
如何将 form
数据从 loginService.js
传递到 Services/index.js
?
How can I pass form
data from loginService.js
to Services/index.js
?
推荐答案
这个问题似乎经常出现,但我似乎找不到规范的答案,所以这里......
This question seems to come up often enough yet I cannot seem to find a canonical answer so here goes...
当从浏览器执行 AJAX 请求时(通过 fetch
或 XMLHttpRequest
),运行时知道对某些请求正文格式做什么,并会自动设置适当的 内容类型
标题
When performing AJAX requests from a browser (via fetch
or XMLHttpRequest
), the runtime knows what to do for certain request body formats and will automatically set the appropriate Content-type
header
如果请求正文是
FormData
实例,Content-type
将设置为multipart/form-data
和还将包括来自数据实例的适当 mime 边界标记.
If the request body is a
FormData
instance, theContent-type
will be set tomultipart/form-data
and will also include the appropriate mime boundary tokens from the data instance.
所有这些示例都将数据发布为 multipart/form-data
并带有适当的 mime 边界标记
All of these examples will post the data as multipart/form-data
with appropriate mime boundary tokens
const body = new FormData()
body.append("foo", "foo")
body.append("bar", "bar")
// fetch
fetch(url, { method: "POST", body })
// XMLHttpRequest
const xhr = new XMLHttpRequest()
xhr.open("POST", url)
xhr.send(body)
// Axios
axios.post(url, body)
如果请求正文是 URLSearchParams
实例,Content-type
将设置为 application/x-www-form-urlencoded代码>
所有这些示例都将数据发布为 application/x-www-form-urlencoded
All of these examples will post the data as application/x-www-form-urlencoded
const body = new URLSearchParams({ foo: "foo", bar: "bar" })
// serialises to "foo=foo&bar=bar"
// fetch
fetch(url, { method: "POST", body })
// XMLHttpRequest
const xhr = new XMLHttpRequest()
xhr.open("POST", url)
xhr.send(body)
// Axios
axios.post(url, body)
如果您打算以特定格式发送字符串数据,则只需手动设置Content-type
,例如text/xml
、application/json
等,因为运行时无法从数据推断类型.
You only need to manually set the Content-type
if you intend to send string data in a particular format, eg text/xml
, application/json
, etc since the runtime cannot infer the type from the data.
fetch(url, {
method: "POST",
headers: {
"Content-type": "application/json",
},
body: JSON.stringify({ foo: "foo", bar: "bar" })
})
在 Axios 上
Axios 为 POST
、PUT提供了默认的
Accept: application/json
和 Content-type: application/json
code> 和 PATCH
请求.它还会自动对传递给 data
参数的 JavaScript 数据结构进行字符串化处理,因此在处理 JSON API 时您只需要最少的配置
On Axios
Axios provides defaults of Accept: application/json
and Content-type: application/json
for POST
, PUT
and PATCH
requests. It will also automatically stringify JavaScript data structures passed into the data
parameter so you only need minimal configuration when dealing with JSON APIs
// no extra headers, no JSON.stringify()
axios.post(url, { foo: "foo", bar: "bar" })
在幕后,Axios 使用 XMLHttpRequest
,因此 FormData
和 URLSearchParams
的规范也适用.
Under the hood, Axios uses XMLHttpRequest
so the specifications for FormData
and URLSearchParams
also apply.
在后端使用 Axios 时,它不会从 FormData
实例推断 Content-type
标头.您可以使用请求拦截器解决此问题.
When using Axios from the backend, it will not infer Content-type
headers from FormData
instances. You can work around this using a request interceptor.
axios.interceptors.request.use(config => {
if (config.data instanceof FormData) {
Object.assign(config.headers, config.data.getHeaders());
}
return config;
});
见https://github.com/axios/axios#form-data
jQuery 的 $.ajax()
方法(以及像 $.post()
这样的便捷方法)默认将请求正文有效负载作为 application/x-www 发送-form-urlencoded
.JavaScript 数据结构将使用 jQuery.param() 自动序列化,除非被告知不要这样做.如果您希望浏览器根据正文格式自动设置Content-type
标题,您还需要在选项中进行配置
jQuery's $.ajax()
method (and convenience methods like $.post()
) default to sending request body payloads as application/x-www-form-urlencoded
. JavaScript data structures will be automatically serialised using jQuery.param() unless told not to. If you want the browser to automatically set the Content-type
header based on the body format, you also need to configure that in the options
const body = new FormData()
body.append("foo", "foo")
body.append("bar", "bar")
$.ajax({
url,
method: "POST",
data: body,
contentType: false, // let the browser figure it out
processData: false // don't attempt to serialise data
})
这篇关于在 Axios 中将数据传递给服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!