2

This is integration issue. Your help is much appreciated (Hint || Guide)

I have both Angular2 and Magento2 (bitnami) installed locally. Magento conf was changed to have the right headers (See below) for CROS. I'm calling Magento2 from Angular2 to get the token and I'm getting the following issue:

OPTIONS http://192.168.56.1:82/magento/index.php/rest/V1/integration/admin/token 400 (Bad Request) XMLHttpRequest cannot load http://192.168.56.1:82/magento/index.php/rest/V1/integration/admin/token. Response for preflight has invalid HTTP status code 400

EXCEPTION: Response with status: 0 for URL: null

Angular 2 side:

let headers = new Headers({'Content-type': 'application/json'});
 headers.append('Access-Control-Allow-Origin', '*');
 headers.append('Access-Control-Allow-Methods', 'GET,POST,OPTIONS,PUT,DELETE');
 headers.append('Access-Control-Allow-Headers', 'Origin,Authorization,X-Auth-Token,Accept,Content-Type');
 headers.append('Access-Control-Allow-Credentials', 'true'); 
 let options = new RequestOptions({ headers: headers });
return this.http.post( 'http://192.168.56.1:82/magento/index.php/rest/V1/integration/admin/token',
                      JSON.stringify('{"username":"angUser", "password":"angUser2017"}'),
                      options)
                      .map(res => res.json());

Magento2 API User angUser / angUser2017 Consumer Key: 5bhvi7gjvyafcp35rajuxh0y4me2plga Consumer secret: yh1nefyw1u80rd0ip1q6f8pijv9x72f1 Access Token: g5plfwth2rhlwtuwfhhqp7mg6sebrxc3 Access Token Secret: i1f4t7j65oo8ydtnteub9xr7wrswe99c

Magento headers: Response Headers Access-Control-Allow-Credentials: True Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization Access-Control-Allow-Methods: GET,POST,OPTIONS,PUT,DELETE Access-Control-Allow-Origin: *

1 Answers1

1

I had a similar issue before and I tracked it down to this method where there is no check for ->isOptions(). So every API call from another domain was triggering a Request method is invalid exception.

/**
 * Retrieve current HTTP method.
 *
 * @return string
 * @throws \Magento\Framework\Exception\InputException
 */
public function getHttpMethod()
{
    if (!$this->isGet() && !$this->isPost() && !$this->isPut() && !$this->isDelete()) {
        throw new \Magento\Framework\Exception\InputException(new Phrase('Request method is invalid.'));
    }
    return $this->getMethod();
}

You can find a possible workaround in the github forum if you are using apache.

In my specific case what I ended up doing was serving both front-end and api from the same domain to avoid problems with CORS (I use nginx).

An example of the configuration needed for this can be something like:

location ~ ^/(index.php/)?rest {
  try_files $uri $uri/ /index.php?$args;
}

location / { 
  root /var/www/angular/public/;
  index index.html;
}
oirad
  • 587
  • 5
  • 7