skip to Main Content

The axios.post (code below) must send data to url api/add-todo, but I get these errors:

enter image description here

  axios.post('http://localhost/vueoctober/todo/api/add-todo', todo).then(function (response) {
    console.log(response);
  }).catch(function(error) {
    console.log(error);
  });

The route api/add-todo is handled with October method Route::get() (https://octobercms.com/docs/services/router). Why is it not found?

If I change axios.post to axios.get it will be working! But I need post data, not get.

What I tried:

1) I tried to add these headers to .htaccess:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTION"

It’s working only for axios.get. The axios.post is still blocking.

2) I added Header set Access-Control-Allow-Origin "*" to httpd.conf.

Vue app is serving at port 8080, therefore axios.post url can’t be relative.

5

Answers


  1. Chosen as BEST ANSWER

    Hours of googling and I got answer...

    1) Install plugin Cross-Origin Resource Sharing (CORS).

    2) In htaccess of Vue app add:

    Header set Access-Control-Allow-Origin '*'
    Header set Access-Control-Allow-Headers "origin, x-requested-with, content-type"
    Header set Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTION"
    

    NOTICE! Write SET not ADD!

    That's it.


  2. Look at the error message carefully, it says the response to the preflight request didn’t have an HTTP ok status.

    Clearly, your server-side code doesn’t have a route handler for the OPTIONS request, so you need to add one.


    As an aside, after the browser gets a successful OPTIONS response, it will make the POST request but you said:

    The route api/add-todo is handled with October method Route::get()

    You’ll need to use Route::post() to handle that.

    Login or Signup to reply.
  3. So for clarification on this. There are always numerous ways to answer a problem. Here is what I did for mine. Check this for Preflight Request. The preflight request is created by the browser and is not for security. This function I created first will throw an okay message upon a request, then if the data contains any data it will then do what it is called (this is where you check for security). I don’t have to mess with .htaccess files. Though I did install the CORS plugin because it is a nice plugin. Also the video from watch-learn does the author is making a cross-origin request in which he goes over how to correct the problem. I think he just filmed the video before preflight requests started to be a browser norm. Found routing information here.

    Route::match(['POST', 'OPTIONS'],'api/update-todo', function(Request $req) {
    $data = $req->input();
    if (!empty($data)) {
        Todo::where('id', $data['id'])
            ->update([
            'name' => $data['name'],
            'description' => $data['description'],
            'status' => $data['status'] 
        ]);
        return response()->json([
            'Success' => $data,
        ]);
    } else {
        return response()->json([
          'Success' => $req,
        ]);
    }
    });
    
    Login or Signup to reply.
  4. I also stumbled and struggled with this on FF, even though I have this in the .htaccess:

    Header set Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS".

    After more searching I found a Gist by @marcomessa that fixed my issues.

    https://gist.github.com/marcomessa/54d077a0208439f5340126ff629a3718

    Login or Signup to reply.
  5. I can not resolve it via axios, I wasted a lot of hours, but I resolved it very easy by this way.

    Let’s think we are posting:

    {name:"Cynthia Merk", age:"22"}
    

    I did the next function to send the last JSON (any JSON structure works):

    const PostFunction = (data, letFunction, errorHandle) => {
        let uri = "http://.../create.php";
        let xhr = new XMLHttpRequest();
        xhr.overrideMimeType("application/json");
        xhr.open("POST", uri, true);
        xhr.addEventListener("readystatechange", function() {
            if(xhr.readyState === 4 && xhr.status === 200) {
                letFunction(this.responseText);
            }else{
                errorHandle(this.responseText);
            }
        });
        xhr.send(JSON.stringify(data));
    }
    

    You can invoke this function, it needs changes the "uri" variable value and it’s required to use JSON.stringify to send the data.

    In PHP the API is very easy too, for dummies:

    <?php
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
        header("Allow: POST, GET, OPTIONS, PUT, DELETE");
    
        class DB extends PDO {
            private $host = 'localhost';
            private $dbname = 'zamuSysScheme';
            private $user = 'root';
            private $password = 'admin';
            private $charset = 'utf8';
    
            public function __construct(){
                try{
                    $dns = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
    
                    parent::__construct($dns, $this->user, $this->password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
    
                } catch(PDOException $e){
                    echo 'Error: ' . $e->getMessage();
                    exit;
                }
            }
    
        }
    
    
        $method = $_SERVER['REQUEST_METHOD'];
    
        $pdo = new DB();
    
        if($_SERVER['REQUEST_METHOD'] == 'POST'){
            $json = file_get_contents('php://input');
            $decoded = json_decode($json, true);
    
            try{
    
                $Name = $decoded["name"];
                $Age = $decoded["age"];
                if(!isset($Name)){
                    header("HTTP/1.1 402 FAIL");
                    echo "The paramenter Name is not present";
                    exit;               
                }
                if(!isset($Age)){
                    header("HTTP/1.1 403 FAIL");
                    echo "The paramenter Age is not present";
                    exit;               
                }
    
                $sqlStatement = "INSERT INTO Client (Name, Age) VALUES";
                $sqlStatement .= "(:Name, :Age)";
                $stmt = $pdo->prepare($sqlStatement);
                $stmt->bindValue(':Name', $Name, PDO::PARAM_INT);
                $stmt->bindValue(':Age', $Age, PDO::PARAM_INT);
                $stmt->execute();
                $Client_Id = $pdo->lastInsertId();
    
                if($Client_Id){
                    header("HTTP/1.1 200 OK");
                    echo $Pago_Id;
                    exit;
                }
    
    
            }catch(Exception $except){
                header("HTTP/1.1 400 FAIL");
                echo "Error: " . $json . " /// " . $except;
                exit;
            }
    
        }
        header("HTTP/1.1 401 BAD REQUEST");
    
    ?>
    

    I hope it can help you, any question is allowed and if I have the answer I’ll glad to help.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search