包含文件时,我在从 React 创建发布请求时遇到了一些问题。我尝试通过排除 .require(:user) 将强参数切换为非强参数。通过这样做,我能够创建一个发布请求,但图像在我的 localhost:3000/users 中没有返回一个 URL。根本没有文件,发布请求可以正常工作。有了它和强大的参数,我得到一个 400 bad request 错误,带有param is missing or the value is empty: user
值。
我在获取请求中的代码是:
import React from 'react'
import {connect} from 'react-redux'
import {fetchUser} from '../actions'
import WelcomePage from './WelcomePage'
class Signup extends React.Component{
state = {
user: {
username: '',
password: '',
pro_pic: null,
currentUser: false
}
}
handleChange = e => {
this.setState({user: {
...this.state.user,
[e.target.name]: e.target.value
}})
}
onImageChange = event => {
this.setState({user: {
...this.state.user,
pro_pic: event.target.files[0] }
});
};
handleSubmit = e => {
e.preventDefault()
const formData = new FormData()
formData.append('username', this.state.user.username);
formData.append('password', this.state.user.password);
formData.append('pro_pic', this.state.user.pro_pic);
this.setState(previousState => {
return {
currentUser: !previousState.currentUser
}
})
fetch('http://localhost:3000/users', {
method: 'POST',
body: ({user: formData})
})
.then(response => response.json())
.then(console.log)
.catch(error=>console.log(error))
}
render(){
return(
<div>
{this.state.currentUser ?
<WelcomePage/>
:
<form onSubmit={this.handleSubmit}>
<input type="text" name="username" placeholder="IGN or Username" value={this.state.username} onChange={this.handleChange}/>
<input type="password" name="password" placeholder="Create Password" value={this.state.password} onChange={this.handleChange}/>
<input type="file" accept="image/*" multiple={false} onChange={this.onImageChange} />
<input type="submit" value="Create Account"/>
</form>
}
</div>
)
}
}
export default connect(null, {fetchUser})(Signup)
我的用户控制器看起来像:
class UsersController < ApplicationController
def index
@users = User.all
render json: @users
end
def show
@user = User.find(params[:id])
render json: @user
end
def create
@user = User.create(user_params)
if @user.valid?
render json: @user
end
end
private
def user_params
params.require(:user).permit(:username, :password, :pro_pic)
end
end
我的用户序列化程序看起来像:
class UserSerializer < ActiveModel::Serializer
include Rails.application.routes.url_helpers
attributes :id, :username, :password, :pro_pic
def featured_image
if object.pro_pic.attached?
{
url: rails_blob_url(object.pro_pic)
}
end
end
end
我已经包含has_one_attached :pro_pic
在我的用户模型中。
编辑: localhost:3000/users 中的内容如下所示:
{
"id": 3,
"username": "asdfsdf",
"password": "zJMFhbSz@DuB74N",
"pro_pic": {
"name": "pro_pic",
"record": {
"id": 3,
"username": "asdfsdf",
"password": "zJMFhbSz@DuB74N",
"created_at": "2020-08-28T14:54:28.845Z",
"updated_at": "2020-08-28T14:54:28.864Z"
}
}
},