【发布时间】:2020-05-29 02:34:19
【问题描述】:
为什么这个请求是一个错误的请求,我在邮递员中发送了相同的请求,使用原始数据和标头内容类型 applications/json 并且它可以工作。 但是在我的 axios 请求中,我收到了错误的请求
const update = dispatch => {
return async (name, email, phone, picture, Age, Blood, Gender, Height, Weight, id) => {
const data = new FormData();
data.append('name', name);
data.append('email', email);
data.append('phone', phone);
data.append('Age', Age);
data.append('Blood', Blood);
data.append('Gender', Gender);
data.append('Height', Height);
data.append('Weight', Weight);
data.append("picture", {
type: 'image/jpg',
uri: picture,
name: 'profilepic.jpg'
});
const config = {
method: 'put',
url: `http://c256474d.ngrok.io/api/userregister/24`,
data: data,
headers: { 'content-type': 'application/json' }
}
await axios(config)
navigate('UserAccount')
}
}
这是服务器端代码,在使用邮递员测试时有效。使用 form-data 发送时不起作用,但在 body 是 raw 和 application/json 的 header 时起作用
public function update(Request $request, $id)
{
// dd($request->all());
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'string|email|max:255',
'phone' => 'string|min:6',
'Age' => 'string',
'Blood' => 'string',
'Gender' => 'string',
'Height' => 'string',
'Weight' => 'string',
'record' => 'string'
]);
if($validator->fails()){
return response()->json($validator->errors()->toJson(), 400);
}
$doc = User::find($id);
if($request->hasFile('picture')){
// Get filename with the extension
$filenameWithExt = $request->file('picture')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('picture')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('picture')->storeAs('public/images', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
$doc->name = $request->input('name');
$doc->email = $request->input('email');
$doc->phone = $request->input('phone');
if($request->hasFile('picture')){
$doc->picture = $fileNameToStore;
}
$doc->save();
return response()->json([
'message' => 'Success',
]);
}
【问题讨论】:
标签: javascript api react-native axios