我已经对此进行了测试,并且我的代码可以在本地运行,但是当我推送到服务器时,出现了CORS错误。这是同一个域,我相信我已正确配置了CORS,但无法解决此错误。任何帮助将不胜感激。
我将我的快速服务器设置为端口80,并在端口80上进行侦听。呼叫肯定命中了它,但由于以下错误而被拒绝:
跨域请求被阻止:“同源起源”策略禁止读取https://website.com:80/nameid处的远程资源。 (原因:CORS请求未成功)
express / server.js
const express = require('express');
const http = require('http');
const path = require('path');
const passport = require('passport');
const morgan = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const session = require('express-session');
const errorhandler = require('errorhandler');
var env = process.env.NODE_ENV || 'development';
const config = require('./config/config')[env];
console.log('Using configuration', config);
require('./config/passport')(passport, config);
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(session(
{
resave: true,
saveUninitialized: true,
cookieName: 'session',
secret: 'random_string_goes_here',
duration: 15 ,
activeDuration: 15,
maxAge: 30
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(morgan('combined'));
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', 'GET,POST,OPTIONS,DELETE,PUT');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.set('port', config.app.port);
require('./config/routes')(app, config, passport);
function ensureAuthenticated(req, res, next) {
console.log("passing the user val", req.session.username)
if( req.session.username){
return next();
}
else{
res.redirect('/login');
}
}
app.use(express.static(path.join(__dirname, 'public')));
app.get('/*', (req, res) => {
res.sendFile(path.join(__dirname, 'public/index.html'));
});
app.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
express / config / routes.js
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
var xmldoc = require('xmldoc');
var DOMParser = require('dom-parser');
module.exports = function (app, config) {
app.get('/', function (req, res) {
res.redirect('/home')
});
app.post('/nameid', cors(), function (req, res) {
nameidjson = ({ 'nameid': nameid});
console.log(nameidjson);
console.log(JSON.stringify(nameidjson));
res.send(JSON.stringify(nameidjson));
})
};
angular / service.ts
getNameID(): Observable<NameIDResult[]> {
const url = 'https://website.com:80/nameid';
const data = ({ });
return this._http.post(url, data)
.pipe(
map((res) => {
console.log(res);
return <NameIDResult[]> res;
})
);
}