简体   繁体   English

Nodejs express,Heroku CORS

[英]Nodejs express, Heroku CORS

The server side of my app was built using Node with express,我的应用程序的服务器端是使用 Node 和 express 构建的,

It was working fine locally, but now I've uploaded to Heroku它在本地运行良好,但现在我已上传到 Heroku

I'm getting CORS errors, even though I've handled it within the app我收到 CORS 错误,即使我已经在应用程序中处理过

index.js索引.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在我的 http 调用中

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以及来自 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这是我从 Heroku 得到的错误,与我请求的路径有关

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

Try to also allow the credentials:尝试还允许凭据:

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", '*');
    res.header("Access-Control-Allow-Credentials", true);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
    next();
});

Edit:编辑:

Also if you want to make a local http call in your heroku app;此外,如果您想在您的 heroku 应用程序中进行本地 http 调用; change改变

private url = 'https://myserver.herokuapp.com/';

to

private url = '/';

Hi I worked out that it was due to Heroku will only install packeges from your dependancies嗨,我发现这是由于 Heroku 只会从您的依赖项中安装包

And what I needed was in my devDependencies, so once I reinstalled as dependancies it worked!我需要的是在我的 devDependencies 中,所以一旦我重新安装为依赖项,它就起作用了!

another possible cause is missing .env variables.另一个可能的原因是缺少 .env 变量。 When deploying a heroku server, all .env variables have to be set via heroku's config vars.部署 heroku 服务器时,必须通过 heroku 的配置变量设置所有 .env 变量。

If the route required a missing .env, for some reason it returns as a CORS error.如果路由需要缺少 .env,由于某种原因,它会作为 CORS 错误返回。

In my case, the jsonwebtoken was looking for process.env.secretkey, so all routes that called for the jsonwebtoken returned with CORS error, while routes that does not require it worked just fine.在我的例子中,jsonwebtoken 正在寻找 process.env.secretkey,所以所有调用 jsonwebtoken 的路由都返回了 CORS 错误,而不需要它的路由工作得很好。

I was having the same issue.我遇到了同样的问题。 I was getting cors error on Heroku.我在 Heroku 上遇到了 cors 错误。 The reason was that my server was producing some errors on Heroku.原因是我的服务器在 Heroku 上产生了一些错误。 Checked my application log on Heroku found out that there was an error of production env variable not defined.检查我在 Heroku 上的应用程序日志,发现未定义生产环境变量的错误。 So I defined my env variable and bingo!所以我定义了我的 env 变量和宾果游戏! there was no further cors error.没有进一步的 cors 错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM