Open freemind12 opened 4 years ago
This is my app.js file:
app.js
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var index = require('./routes/index'); var usersRouter = require('./routes/usersRouter'); var imagesRouter = require('./routes/imagesRouter'); const uploadRouter = require('./routes/uploadRouter'); const Images = require('./models/images'); //const uploadRouter = require('./routes/uploadRouter'); //const favoriteRouter = require('./routes/favoriteRouter') var config = require('./config'); const mongoose = require('mongoose'); //mongoose.set('useCreateIndex', true); mongoose.Promise = require('bluebird'); var passport = require('passport'); var authenticate = require('./authenticate'); // Connection URL const url = config.mongoUrl; const connect = mongoose.connect(url, { //useMongoClient: true, /* other options */ useNewUrlParser: true , useUnifiedTopology: true }); connect.then((db) => { console.log("Connected correctly to server"); }, (err) => { console.log(err); }); var app = express(); // Secure traffic only app.all('*', (req, res, next) => { if (req.secure) { return next(); } else { res.redirect(307, 'https://' + req.hostname + ':' + app.get('secPort') + req.url); } }); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(passport.initialize()); app.use('/', index); app.use('/users', usersRouter); app.use(express.static(path.join(__dirname, 'public'))); app.use('/images',imagesRouter); app.use('/imageUpload',uploadRouter); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); module.exports = app; And this is my `cors.js` file:
const express = require('express'); const cors = require('cors'); const app = express();
const whitelist = ['http://localhost:3000', 'https://localhost:3443', 'http://localhost:4200']; var corsOptionsDelegate = (req, callback) => { var corsOptions; console.log(req.header('Origin')); if(whitelist.indexOf(req.header('Origin')) !== -1) { corsOptions = { origin: true }; } else { corsOptions = { origin: false }; } callback(null, corsOptions); };
exports.cors = cors(); exports.corsWithOptions = cors(corsOptionsDelegate);
And also my imageRouter.js:
imageRouter.js
const express = require('express'); const bodyParser = require('body-parser'); const Images = require('../models/images'); var authenticate = require('../authenticate'); const imagesRouter = express.Router(); const cors = require('./cors'); imagesRouter.use(bodyParser.json()); /* imagesRouter.options('*', cors.cors, (req, res) => { res.sendStatus(200); //res.header('Access-Control-Allow-Origin', "*"); //res.header('Access-Control-Allow-Methods', 'POST'); //res.header("Access-Control-Allow-Headers", "accept, content-type"); //res.header("Access-Control-Max-Age", "1728000"); } ); */ imagesRouter.route('/') .options(cors.corsWithOptions, (req, res) => { res.sendStatus(200); }) .get(cors.cors, (req,res,next) => { Images.find({}) .then((images) => { res.statusCode = 200; res.setHeader('Content-Type', 'application/json'); res.json(images); }, (err) => next(err)) .catch((err) => next(err)); }) module.exports = imagesRouter;
But I get:
Access to XMLHttpRequest at 'https://localhost:3443/images' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. zone-evergreen.js:2828 GET https://localhost:3443/images net::ERR_FAILED scheduleTask @ zone-evergreen.js:2828 scheduleTask @ zone-evergreen.js:386 onScheduleTask @ zone-evergreen.js:273 scheduleTask @ zone-evergreen.js:379 scheduleTask @ zone-evergreen.js:211 scheduleMacroTask @ zone-evergreen.js:234 scheduleMacroTaskWithCurrentZone @ zone-evergreen.js:1118 (anonymous) @ zone-evergreen.js:2861 proto.<computed> @ zone-evergreen.js:1433 (anonymous) @ http.js:2615 _trySubscribe @ Observable.js:42 subscribe @ Observable.js:28 call @ tap.js:16 subscribe @ Observable.js:23 subscribeToResult @ subscribeToResult.js:9 _innerSub @ mergeMap.js:59 _tryNext @ mergeMap.js:53 _next @ mergeMap.js:36 next @ Subscriber.js:49 (anonymous) @ subscribeToArray.js:3 _trySubscribe @ Observable.js:42 subscribe @ Observable.js:28 call @ mergeMap.js:21 subscribe @ Observable.js:23 call @ filter.js:13 subscribe @ Observable.js:23 call @ map.js:16 subscribe @ Observable.js:23 call @ catchError.js:16 subscribe @ Observable.js:23 ngOnInit @ header.component.ts:41 callHook @ core.js:3937 callHooks @ core.js:3901 executeInitAndCheckHooks @ core.js:3842 refreshView @ core.js:11795 refreshComponent @ core.js:13217 refreshChildComponents @ core.js:11508 refreshView @ core.js:11829 renderComponentOrTemplate @ core.js:11903 tickRootContext @ core.js:13379 detectChangesInRootView @ core.js:13413 detectChanges @ core.js:15093 tick @ core.js:42683 _loadComponent @ core.js:42733 bootstrap @ core.js:42659 (anonymous) @ core.js:42251 _moduleDoBootstrap @ core.js:42247 (anonymous) @ core.js:42202 invoke @ zone-evergreen.js:365 onInvoke @ core.js:41257 invoke @ zone-evergreen.js:364 run @ zone-evergreen.js:124 (anonymous) @ zone-evergreen.js:851 invokeTask @ zone-evergreen.js:400 onInvokeTask @ core.js:41235 invokeTask @ zone-evergreen.js:399 runTask @ zone-evergreen.js:168 drainMicroTaskQueue @ zone-evergreen.js:570 Promise.then (async) scheduleMicroTask @ zone-evergreen.js:553 scheduleTask @ zone-evergreen.js:389 scheduleTask @ zone-evergreen.js:211 scheduleMicroTask @ zone-evergreen.js:231 scheduleResolveOrReject @ zone-evergreen.js:841 then @ zone-evergreen.js:967 bootstrapModule @ core.js:42232 ./src/main.ts @ main.ts:11 __webpack_require__ @ bootstrap:79 0 @ main.ts:12 __webpack_require__ @ bootstrap:79 checkDeferredModules @ bootstrap:45 webpackJsonpCallback @ bootstrap:32 (anonymous) @ main.js:1 Show 28 more frames home:1 Access to XMLHttpRequest at 'https://localhost:3443/images' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. zone-evergreen.js:2828 GET https://localhost:3443/images net::ERR_FAILED
This is my
app.js
file:const express = require('express'); const cors = require('cors'); const app = express();
const whitelist = ['http://localhost:3000', 'https://localhost:3443', 'http://localhost:4200']; var corsOptionsDelegate = (req, callback) => { var corsOptions; console.log(req.header('Origin')); if(whitelist.indexOf(req.header('Origin')) !== -1) { corsOptions = { origin: true }; } else { corsOptions = { origin: false }; } callback(null, corsOptions); };
exports.cors = cors(); exports.corsWithOptions = cors(corsOptionsDelegate);
And also my
imageRouter.js
:But I get: