在Nginx上为Node / Angular API允许Cors Origin

时间:2018-10-14 14:48:21

标签: node.js nginx ubuntu-18.04

我知道这可以像重新发布一样解释,但是直到现在为止,我都花了几天的时间努力使这项工作生效。

我绝对不是托管Web应用程序的专家,这就是为什么我阅读很多教程,视频和能帮助我的所有资源的原因。经过几天在这个论坛上阅读以及其他资源而无法完成这项工作后,我得出结论,我绝对需要帮助。

我必须指定我的Web应用程序在开发模式下可以正常工作。

这是我的Nginx块:

upstream btb {
server 127.0.0.1:3000;
}

server {
    listen 80;
    listen [::]:80;

    root /var/www/mydomain.com/html/AngularBee/dist;
    index index.html index.htm index.nginx-debian.html;

    server_name mydomain.com www.mydomain.com;

    location / {

            try_files $uri $uri/ /index.html;

            proxy_set_header 'Access-Control-Allow-Origin' '*';
            proxy_set_header 'Access-Control-Allow_Credentials' 'true';
            proxy_set_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
            proxy_set_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';

            proxy_pass http://btb;
            proxy_http_version 1.1;

            proxy_set_header Connection 'upgrade';
            proxy_set_header Upgrade            $http_upgrade;
            proxy_set_header Host               $host;
            proxy_set_header X-NginX-Proxy      true;
            proxy_cache_bypass                  $http_upgrade;
            proxy_set_header X-Real-IP          $remote_addr;
            proxy_set_header X-Forwarded-For    $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto  $scheme;
    }

listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot


}

#Generate by Certbot
server {

if ($host = www.mydomain.com) {
    return 301 https://$host$request_uri;
} # managed by Certbot


if ($host = mydomain.com) {
    return 301 https://$host$request_uri;
} # managed by Certbot


    return 404; # managed by Certbot
}

这是我的应用程序的入口点:

'use strict';
  const
  express     = require('express'),
  path        = require('path'),
  http        = require('http'),
  bodyParser  = require('body-parser'),
  mysql       = require('mysql'),
  dotenv      = require('dotenv').config(),
  cors        = require('cors');


module.exports = () => {
let server = express(),
    create,
    start;

create = (config) => {
   //Allow cors origin
    server.use(cors());
    let routes = require('./routes/index');

    //Server settings
    server.set('env', config.env);
    server.set('port', config.port);
    server.set('hostname', config.hostname);

    //Middleware that parses json
    server.use(bodyParser.json({limit: '50mb', extended: true}));
    server.use(bodyParser.urlencoded({ limit:'50mb', extended: true}));

    // Point static path to dist
    server.use(express.static('dist'));

    // Catch all other routes and return the index file
    server.get('/', (req, res) => {
      res.sendFile("index.html", {"root": 'C:/dev/myproject/dist'});
    });

  server.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", 'GET, PUT, PATCH, POST, DELETE');
    res.header("Access-Control-Allow-Headers", "Content-Type");
    next();
  });

    //Set up routes by deferring that responsibility to the index.js within the routes folder.
    routes.init(server);

    const connection = mysql.createConnection({
      host     :  config.hostname,
      user     :  config.user,
      password :  config.password
    });

    connection.connect( (error) => {
      if(error){
        console.log('Error Connexion to database');
      }else{
        console.log('Connected to Database');
      }
    });
};

start = () => {
     let hostname = server.get('hostname'),
         port = server.get('port');

     server.listen(port, () => {
         console.log('Express server listening on - http://' + hostname + ':' + port);
     });
};

return{
  create: create,
  start: start
}
};

最后,这是mozilla给我的错误:

    ERROR 
    {…}
​
     error: error { target: XMLHttpRequest, isTrusted: true, lengthComputable: 
     false, … }
​
     headers: Object { normalizedNames: Map(0), lazyUpdate: null, headers: 
     Map(0) 
    }
​
    message: "Http failure response for (unknown url): 0 Unknown Error"
​
    name: "HttpErrorResponse"
​
    ok: false
​
    status: 0
​
    statusText: "Unknown Error"
​
    url: null
​
    <prototype>: Object { constructor: e()
    } 

最后,这是我由chrome给出的错误:

OPTIONS http://127.0.0.1:3000/api/users/login net :: ERR_CONNECTION_REFUSED

e {标题:n,状态:0,statusText:“未知错误”,网址:null,确定:false,...} 错误:ProgressEvent {isTrusted:true,lengthComputable:false,已加载:0,总计:0,类型:“ error”,…} 标头:n {normalizedNames:Map(0),lazyUpdate:null,标头:Map(0)} 消息:“ HTTP失败响应((未知URL):0未知错误)” 名称:“ HttpErrorResponse” 好的:错误 状态:0 statusText:“未知错误” 网址:空 原始:对象

状态0代码表明我是cors允许原点错误……但是,尽管我也尽力使块和节点入口点中的事物保持整洁,但事情还是出错了。

我希望我的帖子足够完整,以便有所帮助,告诉我是否需要更多信息,我们将不胜感激。

0 个答案:

没有答案