Axios请求仅在回调/异步函数内部时才收到CORS错误

I'm using VueJS for an app I am building. The server I have is written in Golang and has been set to accept CORS. In the app, in one of my components, searchBar, I have set it to fetch some data before it is created.

var searchBar = {
    prop: [...],
    data: function() {
        return { ... };
    },
    beforeCreate: function() {
        var searchBar = this;

        axios.request({
            url: '/graphql',
            method: 'post',
            data: {
                'query': '{courses{id, name}}'
            }
        })
        .then(function(response) {
            searchBar.courses = response.data.data.courses;
        });
    },
    methods: { ... },
    template: `...`
};

Axios works perfectly here. It gets the data I need. searchBar has a button which causes it to emit an event which is then picked up by another component, searchResults. Upon receiving the event, searchResults will fetch some data.

var searchResults = {
    data: function() {
        return { ... }
    },
    mounted: function() {
        var sr = this;

        this.$bus.$on('poll-server', function(payload) {
            var requestData = {
                url: '/graphql',
                method: 'post',
                data: { ... },
                ...
            };
            ...

            axios.request(requestData)
                 .then(function(response) {
                     console.log(response);
                 }
            );
        });
    },
    template: `...`
};

Note that my Axios request call is now inside a callback function. When this call is performed, I receive a CORS error:

Access to XMLHttpRequest at 'http://127.0.0.1:9000/graphql' from origin 'http://127.0.0.1:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

My server is located at http://127.0.0.1:9000, with the client in http://127.0.0.1:8080. Here is the content of the OPTIONS request of the second request call.

Second call's OPTIONS method request headers.

For comparison, here is the request header of the first request call (that works!).

First call's OPTIONS method request headers.

I have already set my Golang server to support CORS via go-chi/cors. This is how set it up.

router := chi.NewRouter()
...    
// Enable CORS.
cors := cors.New(cors.Options{
    AllowedOrigins:   []string{"*"},
    AllowedMethods:   []string{"POST", "OPTIONS"},
    AllowedHeaders:   []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
    ExposedHeaders:   []string{"Link"},
    AllowCredentials: true,
    MaxAge:           300,
})

router.Use(
    render.SetContentType(render.ContentTypeJSON),
    middleware.Logger,
    middleware.DefaultCompress,
    middleware.StripSlashes,
    middleware.Recoverer,
    cors.Handler,
)

router.Post("/graphql", gqlServer.GraphQL())

return router, db

What is causing the error I am having and how can it be solved?

查看全部
dongyuan2652
dongyuan2652
2019/04/01 02:58
  • cors
  • axios
  • vue.js
  • javascript
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

3个回复