Post Request working in Postman but returns Preflight error in Angular 2 app

后端 未结 2 1129
长发绾君心
长发绾君心 2021-01-27 05:11

THis is the error log from browser console XMLHttpRequest cannot load http://domain.com/xx/xxxxxxxx. Response for preflight has invalid HTTP status code 404

This is

相关标签:
2条回答
  • 2021-01-27 05:18

    You should send body without JSON.stringify :

    let body = {
      "name": name,
      "recipient": recipient
    };
    

    Good Luck

    0 讨论(0)
  • 2021-01-27 05:22

    In certain cases a browser will automatically perform a preflight request to check the list of allowed methods or verbs before actually sending the reel one. You can see those within your browser's network tab. I guess in Postman you are directly sending the POST request while the pre-sent OPTIONS request should be the failing one.

    Yii has a built-in action which is defined under the ActiveController class to respond to such requests. But in your case you are directly extending its parent controller instead so you'll need to manually define a similar action inside your controllers (or a parent one to them) responding to preflight requests:

    public function actionOptions() 
    {
        if (Yii::$app->getRequest()->getMethod() !== 'OPTIONS') {
            Yii::$app->getResponse()->setStatusCode(405);
        }
    
        $allowed_verbs = ['GET', 'POST', 'HEAD', 'OPTIONS'];
        Yii::$app->getResponse()->getHeaders()->set('Allow', implode(', ', $allowed_verbs));
    }
    

    Also; as you are not using the built-in routing mechanism for REST; in your case you'll also need to manually define rules to that Options action: (edited version of the code from your comments)

    'urlManager' => [ 
        'enablePrettyUrl' => true,
        'enableStrictParsing' => true,
        'showScriptName' => false,
        'rules' => [ 
            'POST <version:[\w-]+>/users/verify' => '<version>/user/verify',
            'POST <version:[\w-]+>/airtime' => '<version>/airtime/airtime',
            'POST <version:[\w-]+>/bulk' => '<version>/routine/index',
            'POST <version:[\w-]+>/contact' => '<version>/contact/index',
    
            // OPTTIONS URI ENDPOINTS
            'OPTIONS <version:[\w-]+>/users/verify' => '<version>/user/options',
            'OPTIONS <version:[\w-]+>/airtime' => '<version>/airtime/options',
            'OPTIONS <version:[\w-]+>/bulk' => '<version>/routine/options',
            'OPTIONS <version:[\w-]+>/contact' => '<version>/contact/options',
        ],
    ];
    
    0 讨论(0)
提交回复
热议问题