0

I have got a file that's name is request.js,

import axios from 'axios'

const baseURL = 'https://SOME_URL.com/api/'

const config = {
  baseURL,
  timeout: 10000,
  headers: {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Headers': '*',
  }
}

const request = axios.create(config)

export default request

and I'm trying to send request in Vuex Actions;

import request from '../request'

const actions = {
  postData(_, payload){
    return request.post('a-request-url', payload)
  }
}

Sending 2 requests and throws a CORS error when I run request. CORS error Access to XMLHttpRequest at 'https://crm.clinic/api/crm/login' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response

AND 2 requests like; enter image description here

enter image description here

enter image description here

and the real problem, cors error continious when deploy my code as production. Can you help me?

3
  • You have to enable it in your backend. Commented Jun 12, 2020 at 7:35
  • @BeHappy you're right but already enabled. I don't understand when I send request with jQuery ajax, or send request in axios with Cors Chrome Extension request is working, but this way not working. Commented Jun 12, 2020 at 7:42
  • Read this: github.com/axios/axios/issues/2345#issuecomment-548950488 Commented Jun 12, 2020 at 7:58

1 Answer 1

4

If you read the second part in the error it says where the issue is.

Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response

As you can see you need to allow access in preflight response. A preflight request is something the browser does before sending your actual GET/POST/etc request. In the devtools' network tab you have 2 requests for the /login url. First one is a preflight using OPTIONS method.

To fix the issue you need to make sure your backend server returns 'Access-Control-Allow-Origin': 'http://localhost:8080' header in it's response for OPTIONS requests. Currently it is specifying only allowed methods and headers. You don't need to add those headers to your axios request.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.