简体   繁体   English

在所有 Axios 请求中发送默认的 POST 变量

[英]Send default POST variable in all Axios requests

I need to add the default global variable to all my POST requests using Axios.我需要使用 Axios 将默认全局变量添加到我的所有 POST 请求中。

I'm able to add the parameter using interceptor like:我可以使用拦截器添加参数,例如:

axios.interceptors.request.use((config) => {
  config.params = config.params || {};
  config.params['timezone_adjust'] = window.timezone_adjust;
  return config;
});

But in this case the url looks like "{url}?timezone_adjust=0但在这种情况下,网址看起来像 "{url}?timezone_adjust=0

However I want to include the timezone_adjust variable on the request data object instead.但是我想在请求数据对象上包含 timezone_adjust 变量。 Is that possible?那可能吗?

If you want to make a "global" settings to all your POST requests you should prefer using headers instead of body payload如果您想对所有POST请求进行“全局”设置,您应该更喜欢使用headers而不是body有效负载

Why?为什么? different requests may have different body payload, yet they can share common headers set (it is more common than shared payload)不同的请求可能有不同的主体有效负载,但它们可以共享公共标头集(这比共享有效负载更常见)

In that case you can use Global axios defaults在这种情况下,您可以使用全局 axios 默认值

axios.defaults.headers.post['YOUR-COMMON-HEADER'] = 'HEADER-VALUE';

Then you should fetch your headers from request object in your backend然后您应该从后端的request对象中获取标头

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM