javascript - 为什么我的 POST 请求不能在浏览器上运行,但它在邮递员中运行,即使我遵循相同的步骤/方式?
问题描述
我试图弄清楚为什么我的代码通过 Postman 成功地将文件名、id 和电子邮件发布到数据库而没有问题,但是当我在浏览器上使用我的代码尝试它时 - 它失败并在日志中给出了这个错误: ErrorException: Trying to get property 'id' of non-object in file
.
在邮递员中,这是我的步骤:
- 使用登录端点成功进行身份验证
- 使用单独的端点成功地将文件名、ID 和电子邮件发布到数据库
我看不出我做错了什么fetch()
。我按照浏览器中的相同步骤执行与 Postman 中的发布请求完全相同的方式。唯一的区别是我使用访问令牌和标头来识别用户是谁,即使在 Postman 中我没有使用访问令牌和标头,但它工作正常,奇怪的是。
如果我删除访问令牌和标头,那么我仍然会在日志中收到上述错误,再次奇怪。
在内部dd($id, $email);
- 它确实在发出发布请求时返回了正确的信息,因此我们可以排除这些变量不是问题。
我做错了什么,我该如何纠正?
前端 React.js 代码:
import React, {Component} from 'react';
import Cookies from 'js-cookie';
class Upload extends Component {
constructor(props) {
super(props);
this.state = {
selectedFile: null,
id: null,
email: '',
fData: ''
};
this.onFormSubmit = this.onFormSubmit.bind(this);
this.onChange = this.onChange.bind(this);
this.fileUpload = this.fileUpload.bind(this);
}
componentDidMount() {
this.getId();
this.getEmail();
}
onFormSubmit(e) {
e.preventDefault();
this.fileUpload(this.state.selectedFile);
}
onChange(e) {
this.setState({ selectedFile: e.target.files[0] });
}
fileUpload(file) {
const formData = new FormData();
const accessToken = Cookies.get("access_token").slice(13,-8);
console.log(accessToken);
formData.append('file', file);
const headers = {
'Contant-Type' : 'application/json',
'Authorization' : 'Bearer ' + accessToken
}
fetch('http://my/api/endpoint/url', {
method: 'POST',
body: formData,
headers: headers
})
.then(response => console.log(response))
.catch(error => { console.error(error) });
}
render() {
return (
<form encType='multipart/form-data' id="login-form" className="form" onSubmit={this.onFormSubmit}>
<input type="file" name="file" onChange={this.onChange}/>
<button type="submit">Upload</button>
</form>
);
}
}
export default Upload;
后端 Laravel 控制器代码:
public function store(Request $request) {
$filePath = $request->file('file')->getClientOriginalName();
$id = $request->user()->id;
$email = $request->user()->email;
// dd($id, $email);
$data = [
'file_path' => $filePath,
'user_id' => $id,
'email' => $email
];
DB::table('db.photos')->insert($data);
echo "Record inserted successfully.<br/>";
}
解决方案
推荐阅读
- php - PHP 将文本转换为查询
- javascript - 更新网页以包含被阻止的 iframe,但初始加载工作正常
- zeromq - ZMQ PUB SUB LOST TCP CONNECTION ON PUB 端
- sql - Oracle 查询 where field1=field2 and field2=field1
- html - 是否可以选择最近的css选择器或父级
- python - python中的平方根循环
- java - 应用程序在不显示权限对话框的情况下崩溃,但在手动授予权限时工作正常
- c - 使用通用案例进行开关改进
- druid - Druid 的数据源列在 Superset 中显示为 STRING
- python - 为什么 scipy.stats.rv_continuous 的这个子类没有在正确的范围内生成随机变量?