我正在尝试通过vuejs表单创建一个新的user
。我在后端使用Rails API。
我正在使用gem knock
和gem bcrypt
进行JWT授权。
提交表单时,终端出现422错误。我注意到的是,它似乎正在尝试将其处理为HTML,而不是json。
Started POST "/api/v1/users" for 127.0.0.1 at 2019-02-17 21:18:05 +0000
Processing by Api::V1::UsersController#create as HTML
Parameters: {"email"=>"ui@gmail.com", "password"=>"[FILTERED]", "user"=>{"email"=>"ui@gmail.com"}}
Completed 422 Unprocessable Entity in 10ms (Views: 0.9ms | ActiveRecord: 0.0ms | Allocations: 576)
使用Insomnia时,我可以很好地创建新用户,这使我专注于解决问题的前端。
此外,当我从has_secure_password
模型中删除user
时,表单成功提交了200,尽管没有密码。
那为什么在这里显示密码?
createuser.vue
<template>
<div class="card-container">
<div class="signup">
<form @submit.stop.prevent="newUser">
<input id="email" v-model="email" type ="text" name="email" class="input">
<input id="password" v-model="password" type="password" name="password" class="input">
<input type="submit" value="Submit" class="btn-update">
</form>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
email: '',
password: '',
errors: []
}
},
methods: {
newUser() {
axios.post('http://localhost:3001/api/v1/users', {
email: this.email,
password: this.password
})
.then(res => (this.user = res.data))
.catch((error) => {
console.log(error)
});
},
}
};
</script>
<style>
</style>
routes.rb
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
post 'user_token' => 'user_token#create'
resources :users
resources :posts
#post '/users/create' => 'users#create' not making a difference
#get '/users/current' => 'users#current'
end
end
end
users_controller.rb
class Api::V1::UsersController < ApplicationController
before_action :authenticate_user, only: [:index, :current, :update]
def index
render json: User.all, status: 200
end
# Call this method to check if the user is logged-in.
# If the user is logged-in we will return the user's information.
def current
current_user.update!(last_login: Time.now)
render json: current_user
end
#def show
# @user = User.find(params[:id])
#
# render json: User.find(params[:id]), status: 200
#end
def create
user = User.new(user_params)
if user.save
render json: user, status: :created, location: user
else
render json: user.errors, status: :unprocessable_entity
end
end
def update
if @user.update(user_params)
render :show, status: :ok, location: @user
else
render json: @user.errors, status: :unprocessable_entity
end
end
def destroy
@user.destroy
end
private
def set_user
@user = User.find(params[:id])
end
def user_params
params.require(:user).permit(:email, :password, :avatar)
end
end
更新
我已经向API名称空间添加了默认选项。
namespace :api, defaults: {format: :json}
这已将处理“纠正”为JSON:
Processing by Api::V1::UsersController#create as JSON
但是我仍然得到422代码。
答案 0 :(得分:0)
您需要将发布数据包装在user
对象中
{
"user":
{
"email": "user@example.com",
"password": "password"
}
}
您可以更改请求
axios.post('http://localhost:3001/api/v1/users', {
user: {
email: this.email,
password: this.password
}
})
.then(res => (this.user = res.data))
.catch((error) => {
console.log(error)
});