本地主机上具有Angular的NodeJS + Express:被CORS预检阻止

时间:2019-06-16 13:05:49

标签: node.js angular cors

我已经尝试了这些帖子中给出的所有解决方案:

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource

How to enable cors nodejs with express?

我尝试使用cors,这似乎是最受欢迎的解决方案,但仍然出现以下错误:

Access to XMLHttpRequest at 'http://localhost:3000/email' from origin 'http://localhost:63342' has been blocked by CORS policy: Method GET' is not allowed by Access-Control-Allow-Methods in preflight response.

这是我的服务器端(NodeJS)设置: 尝试#1 (不使用cors模块)

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var cors = require('cors')
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

function setupCORS(req, res, next) {
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, Content-type,Accept,X-Access-Token,X-Key');
  res.header('Access-Control-Allow-Origin', '*');
  if (req.method === 'OPTIONS') {
    res.status(200).end();
  } else {
    next();
  }
}
app.all('/*', setupCORS);


app.use('/', indexRouter);
app.use('/users', usersRouter);

尝试#2:(带有“ cors”模块)

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var cors = require('cors')
var app = express();
app.use(cors());


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

这些都不起作用,我不知道如何解决。 我正在运行服务器本地主机,这就是我在Angular中进行GET调用的方式:

$scope.getAllCustomerEmails = function() {
        $scope.textBox= "getAllCustomerEmails";

        $http({
            method: "GET'",
            url: "http://localhost:3000/email"
        }).then(function successCallback(response) {
            //console.log("/email response: ", response);
            $scope.textBox = response;

        }, function errorCallback(response) {
            $scope.textBox = "GET Error";
        });
    };

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我认为这会帮助您...

在与package.json文件平行的应用程序的根目录下,创建一个新文件 proxy.config.json

{
   "/api*": {
     "target":"http://localhost:8080", //Add Your Backend url here
     "secure":false,
     "logLevel":"debug"
   }
}

现在在您的 package.json 文件中,在脚本中将其添加为启动方法。

"scripts": {
    "start":"ng serve --proxy-config proxy.config.json",
    "test":"ng test"
}