我有一个使用 Angular 5 的 MEAN 应用程序,我正在尝试将用户重定向到外部 URL,但我不知道为什么在控制台中出现接下来的两个错误
Failed to load https://www.google.com.ar/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
Http failure response for (unknown url): 0 Unknown Error
我已经启用了 CORS,但仍然不起作用
组件 Angular 5
this.http.get('/api/producto').subscribe(data => {
console.log(data);
});
APP.JS
var express = require('express');
var compression = require('compression');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var config = require('./config/database');
var cors = require('cors');
var app = express();
app.use(cors());
app.get('/api/producto', cors(), function (req, res) {
res.status(301).redirect("https://www.google.com.ar")
res.end();
})
app.use(compression());
mongoose.Promise = require('bluebird');
mongoose.connect(config.database, { promiseLibrary: require('bluebird') })
.then(() => console.log('connection succesful'))
.catch((err) => console.error(err));
app.use(passport.initialize());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ 'extended': 'false' }));
app.use(express.static(path.join(__dirname, 'dist')));
app.use('', express.static(path.join(__dirname, 'dist')));
app.use('/', express.static(path.join(__dirname, 'dist')));
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function (err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
如果我转到“http://localhost:3000/api/producto ”,重定向工作正常,但如果组件调用 api,则不起作用
最佳答案
您的代码可能没有执行您想要的操作,但可以正常工作。即使您在后端使用 cors,您发送的响应 /api/producto
也会重定向到 google。
当 Angular 发出调用时,它会重定向到 google 作为响应。然后,前端尝试向 google 发出 ajax 请求,该请求没有 CORS header (只有您的后端响应具有 CORS header )。
如果你想将用户重定向到google,你的后端需要返回状态码为200的url,然后在你的前端你可以重定向该url
this.http.get('/api/producto').subscribe(url=> {
window.location.href = url;
});
关于node.js - res.redirect() cors在MEAN应用程序中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49835830/