VUE 跨域POST请求总是失败

新手上路,请多包涵

1. 问题

Vue调用DjangoRestframework的POST方法总是会被取消发送

2. 代码

api.js

import Vue from 'vue'
import Axios from 'axios';

import VueAxios from 'vue-axios'

import { cookieStorage } from 'src/common/storage'

const myApi = Axios.create({
  baseURL: 'http://localhost:4000/',
  timeout: 5000,
  withCredentials: true,
  transformRequest: [(data) => JSON.stringify(data.data)],
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  }
})

Vue.use(VueAxios, Axios)

//添加请求拦截器
myApi.interceptors.request.use(config => {
    //在发送请求之前做某事
    let token = cookieStorage.get('user_info').token
    if (token) {
        Axios.defaults.headers.common['Authenticate'] = "Token " + token;
    } else {
        Axios.defaults.headers.common['Authorization'] = "";
        console.log(config)
    }
    return config
}, error => {
    console.log(error)
    return Promise.reject(error)
});

export default myApi

login.vue

...
        api.post('/api-token-auth',data = data).then(
          (resp) => {
            console.log(resp.body)
            this.$store.dispatch(SET_USER_INFO,resp.body)
          }
        ).catch((resp)=>{
          console.log(resp.status)
          console.log(resp.body)
        })
      }
    }

3. 错误截图

Chrome Developer

在Chrome://net-internals里看到的信息,说明HTTP请求没能发出去

138028: URL_REQUEST
http://localhost:4000/api-token-auth
Start Time: 2017-08-01 10:57:31.631

t=48317 [st= 0] +REQUEST_ALIVE  [dt=18]
                 --> priority = "MEDIUM"
                 --> url = "http://localhost:4000/api-token-auth"
t=48317 [st= 0]    URL_REQUEST_DELEGATE  [dt=0]
t=48317 [st= 0]   +URL_REQUEST_START_JOB  [dt=18]
                   --> load_flags = 34624 (DO_NOT_SAVE_COOKIES | DO_NOT_SEND_AUTH_DATA | DO_NOT_SEND_COOKIES | MAYBE_USER_GESTURE | VERIFY_EV_CERT)
                   --> method = "OPTIONS"
                   --> url = "http://localhost:4000/api-token-auth"
t=48317 [st= 0]      URL_REQUEST_DELEGATE  [dt=0]
t=48317 [st= 0]      HTTP_CACHE_GET_BACKEND  [dt=0]
t=48317 [st= 0]     +HTTP_STREAM_REQUEST  [dt=18]
t=48317 [st= 0]        HTTP_STREAM_JOB_CONTROLLER_BOUND
                       --> source_dependency = 138030 (HTTP_STREAM_JOB_CONTROLLER)
t=48335 [st=18]        CANCELLED
t=48335 [st=18]     -HTTP_STREAM_REQUEST
t=48335 [st=18]   -URL_REQUEST_START_JOB
                   --> net_error = -3 (ERR_ABORTED)
t=48335 [st=18]    URL_REQUEST_DELEGATE  [dt=0]
t=48335 [st=18] -REQUEST_ALIVE

4. 已经尝试的方法

阅读 6.5k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题