首页 > 解决方案 > 为什么我的 POST 请求不能在浏览器上运行,但它在邮递员中运行,即使我遵循相同的步骤/方式?

问题描述

我试图弄清楚为什么我的代码通过 Postman 成功地将文件名、id 和电子邮件发布到数据库而没有问题,但是当我在浏览器上使用我的代码尝试它时 - 它失败并在日志中给出了这个错误: ErrorException: Trying to get property 'id' of non-object in file.

在邮递员中,这是我的步骤:

  1. 使用登录端点成功进行身份验证
  2. 使用单独的端点成功地将文件名、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/>";
}

标签: javascriptphpreactjslaraveldebugging

解决方案


推荐阅读