What am I missing when making the exact same POST request on browser as I am in Postman that's making it fail?

Viewed 59

In Postman - I'm logging in successfully with login endpoint and after that, I do a file upload which works successfully with the endpoint below. The id and file path get stored successfully in the db. I can conclude that in Postman - after logging in and only attaching one piece of form data (which's the file being uploaded) that the id and email display correct values in Postman. I can confirm it because if I run the dd($id, $email);, the correct values are returned. I'm not attaching email and user id like how I am in my front end code

However, on the browser - I'm trying to send up user id and email but I keep getting a 500 error in the logs that says: "Trying to get property 'id' of non-object".

When I try it on the browser, I'm trying to use access token which would hopefully detect who the user is but that isn't working. What am I doing wrong?

Here's my frontend code:

import React, {Component} from 'react';
import axios from 'axios';

class Upload extends Component {
    constructor(props) {
        super(props);

        this.state = {
            selectedFile: null,
            id: null,
            email: ''
        };
        this.onFormSubmit = this.onFormSubmit.bind(this);
        this.onChange = this.onChange.bind(this);
        this.fileUpload = this.fileUpload.bind(this);
    }

    componentDidMount() {
        console.log("Inside componentDidMount()");
        let id = localStorage.getItem("id");
        let email = localStorage.getItem("email");
        console.log(id);
        console.log(email);
        this.getId(id);
        this.getEmail(email);
    }

    getId(id) {
        console.log("inside getId()");
        this.setState({id: id}, () => console.log(this.state.id));
    }

    getEmail(email) {
        console.log("inside getEmail");
        this.setState({email: email}, () => console.log(this.state.email));
    }

    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 = localStorage.getItem("access_token").slice(13,-8);

        console.log(accessToken);
        console.log(this.state.id);
        console.log(this.state.email);
        formData.append('file', file);

        axios.post('http://myendpoint/api/auth/dash', formData)
            .then(response => {
                console.log(response);
            }).catch(error => {
                console.log(error);
        });
    }

    render() {
        return (
            <form encType='multipart/form-data' id="login-form" className="form" onSubmit={this.onFormSubmit}>
                <input type="file" name="file" id="file" onChange={this.onChange}/>
                <button type="submit">Upload</button>
            </form>
        );
    }

}

export default Upload;

Here's my backend controller code (using Laravel Passport):

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class FileUploadController extends Controller {

    public function store(Request $request) {
        $filePath = $request->file('file')->getClientOriginalName();
        $id = $request->user()->id;
        $email = $request->user()->email;

        // dd($id, $email);

        if (($user = Auth::user()) !== null) {
            $data = [
                'file_path' => $filePath,
                'user_id' => $id,
                'email' => $email
            ];

            DB::table('my.db')->insert($data);
            return response()->json($user);
        }
        return "failed";
    }
}

Here's login method in controller:

public function login(Request $request) {
    $request->validate([
        'email' => 'required|string|email',
        'password' => 'required|string',
        'remember_me' => 'boolean'
    ]);
    $credentials = request(['email', 'password']);
    if(!Auth::attempt($credentials))
        return response()->json([
            'message' => 'Unauthorized'
        ], 401);
    $user = $request->user();
    $tokenResult = $user->createToken('Personal Access Token');
    $token = $tokenResult->token;
    if ($request->remember_me)
        $token->expires_at = Carbon::now()->addWeeks(1);
    $token->save();
    return response()->json([
        'access_token' => $tokenResult->accessToken,
        'token_type' => 'Bearer',
        'expires_at' => Carbon::parse(
            $tokenResult->token->expires_at
        )->toDateTimeString(),
        $user
    ]);
}
0 Answers
Related