Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS - OPTIONS ... 404 (not found)

Hi I'm having a problem with CORS.

GENERAL STRUCTURE:

Angular 4 sends data of a Form to my api. Function saveForm() is executed when I send information about form contact.

app.component.ts

saveForm() {

    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    let requestOptions = new RequestOptions({ headers: headers });

    // Encode JSON as string to exchange data to web server.
    this.data = JSON.stringify(this.myContact);

    this.http.post('https://pablocordovaupdated.herokuapp.com/api', this.data, requestOptions).subscribe(res => {
            let result = res.json();
            if(result['result'] == 'success') {
                this.successMessage = true;
            }
        }
    );

}

Here is the root of problem, because I'm using POST and Content-Type->application/json to send my data and by definition It gives me a problem with CORS - preflighted request, here more definition: Link about preflighted request

This meaning that before angular 4 sends the data to the server, this asks to server if it is available to receive my data with the verb OPTION, if the response of server is OK then angular 4 sends the data of form.

PROBLEM:

In console I always get this error message:

OPTIONS https://pablocordovaupdated.herokuapp.com/api 404 (Not Found)

XMLHttpRequest cannot load https://pablocordovaupdated.herokuapp.com/api. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://pablocordova.herokuapp.com' is therefore not allowed access. The response had HTTP status code 404.

XHR failed loading: POST "https://pablocordovaupdated.herokuapp.com/api".

ERROR Response {_body: ProgressEvent, status: 0, ok: false, statusText: "", headers: Headers…}

WHAT I TRIED:

so far, I understand that problem is because https://pablocordovaupdated.herokuapp.com/api doesn't return answer for verb OPTIONS

then I tried to resolve this of 2 ways:

Using cors package CORS package I configured according documentation.

var express = require('express');
var cors = require('cors');
...
var app = express();
...
app.options('/api', cors());
app.post('/api', cors(), function(req, res, next) {

    // Proccess to send this data via email
    // and also save in data base(only for learning)

});

But I get in console the same error.

Configuring headers manually by Discussion StackOverFlow or Discussion Github

That code is inserted inside every route that I want to write the headers, in my case:

app.post('/api', function(req, res, next) {

    if (req.method === 'OPTIONS') {
          console.log('!OPTIONS');
          var headers = {};
          // IE8 does not allow domains to be specified, just the *
          // headers["Access-Control-Allow-Origin"] = req.headers.origin;
          headers["Access-Control-Allow-Origin"] = "*";
          headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
          headers["Access-Control-Allow-Credentials"] = false;
          headers["Access-Control-Max-Age"] = '86400'; // 24 hours
          headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";
          res.writeHead(200, headers);
          res.end();
    } else {
        // Process to send this data via email
        // and also save in data base(only for learning)
    } 

});

Here the problem is that never execute console.log('!OPTIONS');

Here also I tried simply:

app.post('/api', function(req, res, next) {
    console.log('!I AM YOUR FATHER');
    ...
});

but never is printed. Note: I tried to see this message with heroku logs because the whole page is in Heroku.

But also doing this I get the same error.

MORE INFORMATION:

When the .../api is called, I have this headers

**GENERAL**:

Request URL:https://pablocordovaupdated.herokuapp.com/api
Request Method:OPTIONS
Status Code:404 Not Found
Remote Address:23.21.185.158:443
Referrer Policy:no-referrer-when-downgrade

**RESPONSE HEADERS**:

HTTP/1.1 404 Not Found
Connection: keep-alive
Server: Cowboy
Date: Wed, 10 May 2017 04:14:45 GMT
Content-Length: 494
Content-Type: text/html; charset=utf-8
Cache-Control: no-cache, no-store

**REQUEST HEADERS**:

OPTIONS /api HTTP/1.1
Host: pablocordovaupdated.herokuapp.com
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: POST
Origin: https://pablocordova.herokuapp.com
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Referer: https://pablocordova.herokuapp.com/
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: es-ES,es;q=0.8

QUESTION:

That is my true problem or I am understanding bad? and/or What can I do to solve that problem? and/or Any advices?

Thanks.

like image 804
Pablo Cesar Cordova Morales Avatar asked May 10 '17 05:05

Pablo Cesar Cordova Morales


1 Answers

The problem seems to be that https://pablocordovaupdated.herokuapp.com/api always returns 404:

$ curl -i https://pablocordovaupdated.herokuapp.com/api
HTTP/1.1 404 Not Found

That is, the server isn’t doing anything special/different for the OPTIONS request—instead all requests are just hitting that 404.

app.post('/api', function(req, res, next) {
    console.log('!I AM YOUR FATHER');
    ...
});

I’m not super clear on how Express handles this case, but it may be that must configure it to send some kind of response for that route—not just a console.log on the server side.

When I look at the content of https://pablocordovaupdated.herokuapp.com/api what I see is just a generic Heroku 404 page—so it’s not being served from your app but instead falling back to being served by Heroku. For example, the contents of that 404 page have this:

<iframe src="//www.herokucdn.com/error-pages/no-such-app.html"></iframe>

That is, it appears to be that request for that URL are never getting handled as expected by your app code at all under any circumstances. So it seems like that’s what you need to fix first.

like image 76
sideshowbarker Avatar answered Sep 28 '22 22:09

sideshowbarker