![](/img/trans.png)
[英]How come in Postman my post request works but not in the browser even though I'm doing the same?
[英]Why won't it POST my data successfully even though it works on Postman?
我已经使用正确的键和值在 Postman 上测试了我的端点,它工作正常。 但是,当我尝试在浏览器上发出 POST 请求时 - 我收到500
错误。
console.log(id);
和console.log(email);
都打印正确的值,所以我可以排除这不是问题。 我也尝试过使用Axios
发出 POST 请求,但它一直给我带来问题,所以我恢复为fetch
。 我愿意接受有关改进我的代码的任何建议:)。
如何在浏览器上成功发送我的帖子请求 go? 我可能忽略了一些东西
前端代码:
fileUpload(file) {
const formData = new FormData()
let id = Cookies.get("id");
let email = Cookies.get("email");
console.log(id);
console.log(email);
formData.append('file', file);
this.setState({
id: id,
email: email,
formData: formData
});
let data = {
"id": this.state.id,
"email" : this.state.email,
"formData": this.state.fData
}
fetch('http://myendpoint/api/auth/wall-of-fame', {
method: 'POST',
body: data
})
.then(response => console.log(response))
.catch(error => { console.error(error) });
}
后端代码:
public function store(Request $request){
$filePath = $request->file('file')->getClientOriginalName();
$id = Auth::user()->id;
$email = Auth::user()->email;
$data= [
'file_path' => $filePath,
'user_id' => $id,
'email' => $email
];
DB::table('my db')->insert($data);
echo "Record inserted successfully.<br/>";
}
当您使用表单数据上传文件时,最好将其他属性添加到表单数据本身,如下所示,而不是创建数组
formData.append('file', file)
formData.set('id', id)
formData.set('email', email)
此外,在请求中,您可以将 formData 作为正文发送
fetch('http://myendpoint/api/auth/wall-of-fame', {
method: 'POST',
body: formData
})
这应该可以解决您的问题。 让我知道
使用来自前端的@wk24 答案,并在后端代码中使用 AUTH 来获取用户 ID 而不是 $request,我认为你应该使用
$request->id;
$email = $request->email;
希望这能解决你的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.