我尝试在标头而不是网址中发送api密钥,但是收到错误。
卷曲一切都没问题。我对了json hash:
curl -H "Token: 01PMn25BCj-sluxchSM" http://localhost:3000/api/posts
但是Angular给了我这个问题:
XMLHttpRequest cannot load http://localhost:3000/api/users/croaton/tags. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3001' is therefore not allowed access. The response had HTTP status code 404.
Rails config
def cors_set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'
headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, Accept, Authorization, Token'
headers['Access-Control-Max-Age'] = "1728000"
end
def cors_preflight_check
if request.method == 'OPTIONS'
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'
headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-Prototype-Version, Token'
headers['Access-Control-Max-Age'] = '1728000'
render :text => '', :content_type => 'text/plain'
end
end
def authenticate
api_key = request.headers['Token']
@user = User.where(api_key: api_key).first if api_key
unless @user
head status: :unauthorized
return false
end
end
Angular config
RestangularProvider.setDefaultHeaders({'Token': '01PMn25BCj-sluxchSM'});
获取json
return Restangular.all('posts').getList();