0

I'm following a tutorial to upload photos using laravel + reactjs. In the tutorial, the author uses http://localhost:8000/api/fileupload but I'm not sure where to find my own?

https://appdividend.com/2018/03/23/react-js-laravel-file-upload-tutorial/

I've looked around but can't seem to find the answer this seemingly obvious question.

What am I doing wrong and how can I fix this?

Upon uploading the image by clicking the Upload button, I get an error in the console, below.

Access to XMLHttpRequest at 'http://localhost:8000/api/fileupload' 
from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: No 
'Access-Control-Allow-Origin' header is present on the requested 
resource.

POST http://localhost:8000/api/fileupload net::ERR_FAILED


Uncaught (in promise) Error: Network Error
at createError (app.js:653)
at XMLHttpRequest.handleError (app.js:188)

Here's my .env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=app
DB_USERNAME=root
DB_PASSWORD=root

Here's my JS:

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

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

        this.state = {
            image: ''
        };

        this.onFormSubmit = this.onFormSubmit.bind(this);
        this.onChange = this.onChange.bind(this);
        this.fileUpload = this.fileUpload.bind(this);
    }

    onFormSubmit(e) {
        e.preventDefault();
        this.fileUpload(this.state.image);
    }

    onChange(e) {
        let files = e.target.files || e.dataTransfer.files;
        if(!files.length) {
            return;
        }
        this.createImage(files[0]);
    }

    createImage(file) {
        let reader = new FileReader();
        reader.onload = (e) => {
            this.setState({
                image: e.target.result
            });
        };
        reader.readAsDataURL(file);
    }

    fileUpload(){
        const url = 'http://localhost:8000/api/fileupload';
        const formData = {file: this.state.image};
        let post = axios.post(url, formData)
            .then(res => {
                console.log(res);
                console.log("sent?");
            });
        return post;
    }

    render() {
        return (
            <form onSubmit={this.onFormSubmit}>
                <h1>File Upload</h1>
                <input type="file" />
                <button type="submit" onClick={this.fileUpload}>Upload</button>
            </form>
        );
    }
}

export default Wall;

Here's create_fileuploads_table:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Here's FileuploadController.php:

<?php

 namespace App\Http\Controllers;

 use Illuminate\Http\Request;
 use App\Fileupload;


class FileuploadController extends Controller
}

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        if($request->get('file'))
        {
            $image = $request->get('file');
            $name = time().'.' . explode('/', explode(':', substr($image, 0, strpos($image, ';')))[1])[1];
            \Image::make($request->get('file'))->save(public_path('images/').$name);
        }
        $fileupload = new Fileupload();
        $fileupload->filename=$name;
        $fileupload->save();
        return response()->json('Successfully added');
    }


}

Here's FileUpload.php:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Fileupload extends Model
{
    public function user() {
        return $this->belongsTo(User::class);
    }

}
luvs2spuge
  • 75
  • 5
  • `No 'Access-Control-Allow-Origin' header is present on the requested resource` Your site is on the domain 127.0.0.1 and you want to access localhost. change either to match the other – seven_seas Aug 16 '19 at 01:36
  • Possible duplicate of [Why does my JavaScript code get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when Postman does not?](https://stackoverflow.com/questions/20035101/why-does-my-javascript-code-get-a-no-access-control-allow-origin-header-is-pr) – seven_seas Aug 16 '19 at 01:37
  • Can you post a link to the tutorial you're following? That may better help contributors provide feedback. – Kyle Pendergast Aug 16 '19 at 01:37
  • 1
    @KylePendergast done, was gonna do that earlier but slipped my mind. – luvs2spuge Aug 16 '19 at 01:40
  • Have you tried from localhost? – joseluismurillorios Aug 16 '19 at 01:43
  • @joseluismurillorios if by trying from localhost you're referring to `http://localhost:8000`, yes and I get the same error. – luvs2spuge Aug 16 '19 at 01:45
  • I don't see your server code posted. Did you create it? In the second part of the tutorial, it goes over this. If you haven't, then that's probably the largest problem. If you don't have a server set up to receive the requests, then there is nowhere for the image to go. As others have also mentioned, it looks like you are making your request from http://127.0.0.1:8000 which isn't right. You'll need to make it from localhost. – Kyle Pendergast Aug 16 '19 at 02:04
  • @KylePendergast yeah I've gone through the whole tutorial, I can post my server code, I even modified it. I'll post it. – luvs2spuge Aug 16 '19 at 02:08
  • @KylePendergast posted it. – luvs2spuge Aug 16 '19 at 02:13

1 Answers1

0

Have you tried enabling CORS on laravel? if not check this link

Yasii
  • 1,702
  • 1
  • 10
  • 15