2016-12-01 49 views
0

我知道这个qquestion问了好几次,但没有解决我的问题。我使用axios从服务器获取标记(​​)。我在本地主机上工作。我也提供了标题,但仍然出现No 'Access-Control-Allow-Origin' header is present的错误。这个错误是从我的js代码(axios)产生的还是它在服务器中的问题?没有'Access-Control-Allow-Origin'标题出现在请求的资源

const config = { 
    method: 'get', 
    url: `${API_URL}/token`, 
    headers: { 
     'Access-Control-Allow-Origin': '*', 
     'Content-Type': 'application/json', 
     }, 
    }; 

export function getToken() { 
    return function (dispatch) { 
    console.log('action triggered atleast'); 
    axios.request(config) 
    .then(response => { 
     console.log('response', response); 
     localStorage.setItem('token', response.data.token); 
     dispatch({ type: GET_TOKEN }); 
    }) 
    .catch(error => { 
     errorHandler(dispatch, error.response, TOKEN_ERROR); 
    }); 
    }; 
} 

我做了任何错误或错过了我的代码中的东西?

UDPATE

add_header 'Access-Control-Allow-Origin' "*"; 
     add_header 'Access-Control-Allow-Credentials' 'true'; 
     add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; 
     add_header 'Access-Control-Allow-Headers' 'X-CustomHeader,Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With'; 
     # required to be able to read Authorization header in frontend 
     add_header 'Access-Control-Expose-Headers' 'Authorization' ; 

if ($request_method = 'OPTIONS') { 
     # Tell client that this pre-flight info is valid for 20 days 
     add_header 'Access-Control-Max-Age' 1728000; 
     add_header 'Content-Type' 'text/plain charset=UTF-8'; 
     add_header 'Content-Length' 0; 
     return 204; 
} 

以上就是我的nginx的配置。

回答

2

服务器需要发送的CORS头不要求背

到这里看看如何启用CORS:http://enable-cors.org/server.html

如果您没有访问服务器,那么也许你想尝试类似于cors proxy

+0

所以在前端没有问题。问题出在服务器上。我有nginx服务器,我需要通过做这样的'Access-Control-Allow-Origin'来启用CORS:'*',但以其自己的方式不是js方式? – Serenity

+0

纠正问题出在服务器(nginx) – Endless

+0

谢谢,我从你的理解和你分享的链接。在大多数这样的问题中,我看到使用头和服务器问题的地方,所以我搞不清究竟是什么问题。再次感谢您的支持和帮助。 – Serenity

相关问题