【发布时间】:2016-08-17 21:11:37
【问题描述】:
我正在使用 AngularJS,它使用 Ruby on Rails API 进行身份验证。我在 AngularJS 中使用 $http 服务使用 POST 请求向后端注册用户,但是,我很困惑,因为我得到的响应总是以 HTML 形式返回,它是索引页面,而不是来自的实际数据导轨 API。我在本地环境中测试这个,AngularJS 应用程序在 localhost:9000 上运行,Rails API 在 localhost:3000 上。 AngularJS 使用代理将请求定向到端口 3000。
我已经使用 curl 命令测试了 Rails API 的响应:
$ curl -H "Content-Type: application/json" -d '{"user":{"email":"hi@hi.com","password":"12345678"}}' -X POST http://localhost:9000/api/users.json
从服务器返回响应为:
{"success":true,"info":"Registered","data":{"user":{"id":5,"created_at":"2016-04-24T14:13:24.289Z","updated_at":"2016-04-24T14:13:24.298Z","email":"hi@hi.com","authentication_token":"-49zyhbCiddYdjssQx6i"},"auth_token":"-49zyhbCiddYdjssQx6i"}}
这是前端的代码,位于 AngularJS 控制器中:
$scope.register = function() {
$http({
url: '/api/users',
method: 'POST',
data: {
user: $scope.user
}
}).then(
// success
function(response) {
console.log(response.data);
console.log(response.auth_token);
tokenHandler.set( response.auth_token );
$location.path('/');
},
// error
function(response) {
$scope.user.errors = response;
});
};
这是服务器响应代码:
class Users::RegistrationsController < Devise::RegistrationsController
respond_to :json
def create
build_resource(sign_up_params)
if resource.save
sign_in resource
render status: 200,
json: {
success: true,
info: "Registered",
data: {
user: resource,
auth_token: current_user.authentication_token
}
}
else
# Otherwise fail
render status: :unprocessable_entity,
json: {
success: false,
info: resource.errors,
data: {}
}
end
end
end
但是,当我调用 register 方法时,响应总是在 HTML 和我前端的索引文件中。
我错过了什么吗?
【问题讨论】:
-
在您的
curl调用中,您的URL 是http://localhost:9000/api/users.json,而在您的$http调用中,URL 是/api/users -
我尝试在 $http 调用中使用localhost:9000/api/users.json,但它的响应相同,索引页面的 HTML。
标签: ruby-on-rails angularjs ruby rest restful-authentication