如何在VueJS中向Axios调用添加标头?

时间:2018-05-21 16:55:05

标签: ajax curl vue.js vuejs2 axios

我在php代码中有HTTP调用:

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $urlForTheCallGoesHere);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);    
  $data = curl_exec($ch);
  curl_close($ch);

我现在需要转换它以转换为VueJS Axios来电。 到目前为止我所知道的是,Axious调用可以创建为:

  axios.get(urlForTheCallGoesHere)
    .then(res => {
      console.log(responseData)
      //do something with the responseData
    })
    .catch(errorData => {
      console.log(errorData)
      //do something with the errorData
    })
  }

我知道调用的自定义参数可以像这样添加(例子):

  axios.post(exampleUrlForSomeRegistrationLink, {
    email: "exampleEmail@gmail.com",
    password: "examplePassword"
  }).then(res => {
    console.log(responseData)
    //do something with the responseData
  }).catch(errorData => {
    console.log(errorData)
    //do something with the errorData
  })

而且我也知道可以通过分配默认值或使用拦截器来操纵请求/响应(例如在 main.js 条目文件中):

//using default values
axios.defaults.baseURL = 'http://changeTheUrlForTheCallExample.com';
axios.defaults.headers.common['Authorization'] = 'exampleValue';
axios.defaults.headers.get['Accepts'] = 'application/json';

//using interceptors
const reqInterceptor = axios.interceptors.request.use(config => {
  console.log('Request Interceptor', config)
  return config
})
const resInterceptor = axios.interceptors.response.use(res => {
  console.log('Response Interceptor', res)
  return res
})

但是由于以上所有,我仍然不确定如何将PHP代码转换为VueJS代码(使用Axios)。主要问题是如何添加选项的值 CURLOPT_RETURNTRANSFER,CURLOPT_FOLLOWLOCATION和CURLOPT_SSL_VERIFYPEER 如上

0 个答案:

没有答案