Reyem
Reyem

Reputation: 14

Yii2 RestFull API - Error 404 on production with few actions onlyy

I have a problem, I created many actions for an API using Yii2. I have met a recent problem: while everything works on localhost, when I upload on the server, the below actions return a 404 error.

I have been trying many different solution (try to create another controller) with no success

The goal of those functions is to upload/delete images.

config/main.php

      'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => require 'urls.php',
        ],

config/urls.php

    'POST api/controller/<id>/logo-upload' => 'controller-name/logo-upload',
    'POST api/controller/<id>/background-image-upload' => 'controller-name/background-image-upload',
    'POST api/controller/<id>/gallery-upload' => 'controller-name/update-gallery',
    'POST api/controller/<id>/delete-logo' => 'controller-name/delete-logo-image',
    'POST api/controller/<id>/delete-background' => 'controller-name/delete-background-image',
    'POST api/controller/<id>/gallery/<galleryID>/delete' => 'controller-name/delete-gallery-image',

Here a sample controller I created. I changed some variable names or class names but nothing that doesn't change the logic.

controller-name.php

    <?php


namespace frontend\controllers;

use yii\rest\ActiveController;
use yii\filters\Cors;
use yii\helpers\ArrayHelper;
use yii\filters\ContentNegotiator;
use yii\web\Response;
use yii\helpers\BaseJson;
use yii\data\ActiveDataProvider;
use yii\web\UploadedFile;
use Yii;


class Controller extends RestController
{


    public $modelClass = 'common\models\Model';

    public function actions()
    {
        $actions = parent::actions();

        unset($actions['delete'], $actions['create'], $actions['update'], $actions['index'], $actions['options']);

        return $actions;
    }

    public function behaviors()
    {

        return ArrayHelper::merge([
            [
                'class' => Cors::className(),
                'cors' => [
                    'Origin' => ['*'],
                    'Access-Control-Request-Method' => ['GET', 'HEAD', 'OPTIONS', 'POST'],
                ],
            ],
            [
                'class' => 'yii\filters\ContentNegotiator',
                'only' => ['view', 'index', 'update'],  // in a controller
                // if in a module, use the following IDs for user actions
                // 'only' => ['user/view', 'user/index']
                'formats' => [
                    'application/json' => Response::FORMAT_JSON,
                ],
                'languages' => [
                    'en',
                    'fr',
                ],
            ]
        ], parent::behaviors());
    }



    protected function verbs()
    {
        return [
            'index' => ['GET', 'HEAD'],
            'view' => ['GET', 'HEAD'],
            'create' => ['POST'],
            'update' => ['POST', 'PUT', 'PATCH'],
            'delete' => ['DELETE'],
        ];
    }

    protected function findModel($id)
    {
        if (($model = Model::findOne($id)) !== null &&
            (Yii::$app->user->identity->isAdmin() || $model->owner_id === Yii::$app->user->id)
        ) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    public function actionLogoUpload($id)
    {
      $card = $this->findModel($id);
      $image = Image::upload($card, 'logoImageFile');
      if ($image->errors) {
        return $result = ["success"=>false, "message"=> $image->getErrors()];
      }
      if (!empty($image)) {

          $card->image_id = $image->id;
          if ($card->validate() && $card->save()) {
            $result = [
                "success"
            ];
            // }
            return $result;
          } else {
            return $result = ["success"=>false, "message"=> $card->getErrors()];
          }
      }

    }

}

Edit

Okay removing Content-type:multipart/form date in the header makes the route working, but obviously the code doesn't work since no file is sent.

Upvotes: 1

Views: 376

Answers (2)

Reyem
Reyem

Reputation: 14

Okay turned out there was an extra space in the request. The code is fine.

Upvotes: 0

smsalisbury
smsalisbury

Reputation: 375

The problem is likely with your server configuration. You have to configure your server to rewrite unknown paths to your index.php script.

For example, when I've used yii2 with apache, I have the following web/.htaccess file:

# use mod_rewrite for pretty URL support
RewriteEngine on

# If a directory or a file exists, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward the request to index.php
RewriteRule . index.php

# ...other settings...
Options +FollowSymLinks

Of course, a lot of the details are dependent on your hosting and server configuration (e.g. are .htaccess files allowed). Yii's docs have more information on configuring different web servers here.

Upvotes: 1

Related Questions