Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs express, Heroku CORS

The server side of my app was built using Node with express,

It was working fine locally, but now I've uploaded to Heroku

I'm getting CORS errors, even though I've handled it within the app

index.js

var express = require('express');
var bodyParser = require('body-parser');

var http = require('http');
var path = require('path');
var twit = require('twitter');
var app = express();
var port = process.env.PORT || 3000;

var twitter = new twit({
  consumer_key:  'myKey',
  consumer_secret: 'mySecret',
  access_token_key: 'myKey',
  access_token_secret: 'mySecret'
});
app.set('port', (port));
var server = http.createServer(app).listen(port, function() {
  console.log('Server listening on port ' + port);
});
app.use(bodyParser.urlencoded({extended: true}));

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
    next();
});

app.get('/gettweets', function (req, res) {
  twitter.get('statuses/user_timeline', { id: 23445555, count: 3 }, function(err, tweets, response) {
      if (!err) {
         res.json(tweets);
      }
      else {
        return res.status(500).json({
          title: 'An error has occured',
          error: err
        })
      }
    })
})

And in my http call

export class SocialService {

  private url = 'https://myserver.herokuapp.com/';
  constructor(private http: Http) { }

  initialise(){
    var headers = new Headers();
        headers.append('Content-Type', 'application/json');

    return this.http.get(this.url+'gettweets', {headers: headers})
        .map((response: Response) => {
        console.log(response.json());
          return response.json();
        })
        .catch((error: Response) =>  Observable.throw(error.json()) )

  }

}

And the build log from Heroku

-----> Node.js app detected
-----> Creating runtime environment

       NPM_CONFIG_LOGLEVEL=error
       NPM_CONFIG_PRODUCTION=true
       NODE_VERBOSE=false
       NODE_ENV=production
       NODE_MODULES_CACHE=true
-----> Installing binaries
       engines.node (package.json):  unspecified
       engines.npm (package.json):   unspecified (use default)

       Resolving node version 6.x via semver.io...
       Downloading and installing node 6.10.3...
       Using default npm version: 3.10.10
-----> Restoring cache
       Loading 2 from cacheDirectories (default):
       - node_modules
       - bower_components (not cached - skipping)
-----> Building dependencies
       Installing node modules (package.json)
-----> Caching build
       Clearing previous node cache
       Saving 2 cacheDirectories (default):
       - node_modules
       - bower_components (nothing to cache)
-----> Build succeeded!
-----> Discovering process types
       Procfile declares types     -> (none)
       Default types for buildpack -> web
-----> Compressing...
       Done: 17.8M
-----> Launching...
       Released v5
       https://myserver.herokuapp.com/ deployed to Heroku

And error in Browser

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

This is the error I'm getting from Heroku, something to do with the path I'm requesting

2017-05-11T12:54:05.960151+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=OPTIONS path="/gettweets" host=maleonserver.herokuapp.com request_id=5c052790-67df-4677-be8b-14cc2bc71292 fwd="5.67.244.130" dyno= connect= service= status=503 bytes= protocol=https
like image 237
Rasta Avatar asked May 11 '17 12:05

Rasta


People also ask

How do I fix heroku error CORS?

Append the proxy server to your API URL. You may get the 403 forbidden error even after adding the Heroku CORS proxy URL. To fix this, you need to request temporary access to the Heroku Proxy Server by going to the below URL.

Is CORS included in Express?

Enabling CORS The easiest way to get CORS working in Express is by using the cors npm module. That's it. CORS is now enabled. The Access-Control-Allow-Origin header determines which origins are allowed to access server resources over CORS (the * wildcard allows access from any origin).

Can I host a Node JS app on Heroku?

Using CORS in a Heroku app with the cors npm package in node.js I have been experimenting with making node.js applications that I can then deploy to Heroku lately. Heroku is a great way to host a node.js app up on the web for free, so there is no pressure when it comes to spending money each month just to host some simple hobby, test, or demo app.

How to use Cors within a NodeJS application?

To use CORS within a Node.js application, you need the cor package provided by the Node.js NPM registry. Go ahead and install CORS alongside the following other packages using the below command. Below is a simple index.js express server.

How to build an app with Express in Heroku?

Heroku relies on you providing a package.json file to know this is a Node.js project when it builds your app ⚠️ Next, install Express. Express is a widely used server framework for NodeJS. Finally, you are ready to start coding! The next step is to create a file called app.js, which runs an Express server locally.

Is Cors npm package an express framework?

So the cors npm package is an express middleware, so this means I will have to install the express framework along with cors in the project. For this project I made just a single index.js file that makes a simple express app.


1 Answers

Hi I worked out that it was due to Heroku will only install packeges from your dependancies

And what I needed was in my devDependencies, so once I reinstalled as dependancies it worked!

like image 119
Rasta Avatar answered Sep 30 '22 15:09

Rasta