简体   繁体   中英

Respond to ajax request with a string in Rails

I am trying to use respond_with in a Rails 4 controller to respond to an ajax request from an AngularJS app. I just want to return a json web token (string), not an active record object. How do I do this?

I am getting very weird errors about a url being undefined or location being nil. Any help will be greatly appreciated.

Sessions Controller:

class SessionsController < ApplicationController

    respond_to :json

    def new
    end

    def create
        user = User.find_by(email: params[:session][:email].downcase)
        if user && user.authenticate(params[:session][:password])
            #login
            token = log_in(user)
        else
            #error
        end
        respond_with(token)
    end

end

Route:

post 'sessions/create' => 'sessions#create', defaults: { format: :json }

Latest error:

undefined method 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9_url' for #<SessionsController:0x007ff8d0a42f10>

我通过以下方法进行工作:

render json: token, status: 200

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM