node.js - Nodejs express ,Heroku CORS

标签 node.js angular express heroku

我的应用程序的服务器端是使用 Node 和 express 构建的,

它在本地工作正常,但现在我已经上传到 Heroku

我收到 CORS 错误,即使我已经在应用程序中处理了它

索引.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

最佳答案

尝试也允许凭据:

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 = '/';

关于node.js - Nodejs express ,Heroku CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43915577/

相关文章:

Node.js中间件和js封装

Node.js 需要多次或将包作为参数传递?

selenium - Angular 2 Go Protractor 无法访问 getSize() 属性

node.js - 如何确定 Node.js 发送 HTTP 响应正文所花费的时间?

node.js - 读取 pug 中的 window.navigator.language

Node.js 路由发送到不正确的 Controller

javascript - Graphql 需要外部模块与 GraphQLObjectType 内部模块

angular - json-server 中嵌套端点的自定义路由

angular - HttpEventType.UploadProgress 并非来自 Asp.NET MVC

JavaScript - Express - MongoDb - Mongoose findOneAndUpdate 返回未定义