NodeJS 节点快车,Heroku CORS

camsedfj  于 2022-12-22  发布在  Node.js
关注(0)|答案(4)|浏览(138)

我的应用程序的服务器端是使用Node with express构建的,
它在本地运行良好,但现在我已经上传到Heroku
我收到CORS错误,尽管我已在应用程序中进行了处理
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
        })
      }
    })
})

在我的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()) )

  }

}
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

和浏览器错误

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.

这是我从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
ldioqlga

ldioqlga1#

尝试同时允许凭据:

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();
});
    • 编辑:**

另外,如果你想在你的heroku应用程序中进行本地http调用;变化

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

private url = '/';
hiz5n14c

hiz5n14c2#

另一个可能的原因是缺少.env变量。当部署heroku服务器时,所有的.env变量必须通过heroku的配置变量设置。
如果路线需要缺少的.env文件,出于某种原因,它将作为CORS错误返回。
在我的例子中,jsonwebtoken正在查找process.env.secretkey,因此所有调用jsonwebtoken的路由都返回CORS错误,而不需要它的路由则工作正常。

bf1o4zei

bf1o4zei3#

它解决了,这个问题是由Heroku只安装包从您的依赖项和我需要的是在devDependencies,所以一旦我重新安装为依赖项它的工作!

v9tzhpje

v9tzhpje4#

我遇到了同样的问题。我在Heroku上遇到了cors错误。原因是我的服务器在Heroku上产生了一些错误。检查了我在Heroku上的应用程序日志,发现有一个错误是没有定义生产env变量。所以我定义了我的env变量,答对了!没有进一步的cors错误。

相关问题