简体   繁体   中英

Why won't it POST my data successfully even though it works on Postman?

I've tested my endpoint on Postman with the correct key and value and it works fine. However, when I try to make the POST request on the browser - I get a 500 error.

The console.log(id); and console.log(email); are both printing correct values so I can rule out that this isn't the issue. I've also tried using Axios to make the POST request but it kept giving me problems so I restored to fetch instead. I'm open to any suggestions on improving my code:).

How can I make my post request go through successfully on the browser? I'm probably overlooking something

frontend code:

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) });
}

backend code:

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/>";
}

When you are using form data to upload the file, it's better to add other attributes to the form data itself as below rather than creating an array

formData.append('file', file)
formData.set('id', id)
formData.set('email', email)

and further, in the request, you can send the formData as the body

fetch('http://myendpoint/api/auth/wall-of-fame', {
    method: 'POST',
    body: formData
})

this should solve your issue. Let me know

use @wk24 answer from Frontend and in the backend code you are using AUTH to get user id instead of $request, i think you should use

$request->id; $email = $request->email; Hope this solves your problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM