I repeatedly receive type errors and empty responses from what may be a CORS issue. I am new to nodejs and am having problems enabling CORS in my application. What is wrong with the following configuration for app.js, where I tried to apply
app.all('*',function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
immediately after var app = express();
Here is the full app.js file:
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 routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
app.all('*',function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// 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(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
I consistently receive:
OPTIONS http://104.236.99.212:6790/ net::ERR_EMPTY_RESPONSE
undefined:1 Uncaught (in promise) TypeError: Failed to fetch(…)
Any help would be really appreciated! Thank you
In your ExpressJS app on node.js, do the following with your routes:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/', function(req, res, next) {
// Handle the get for this route
});
app.post('/', function(req, res, next) {
// Handle the post for this route
});
Related
I send a post request to my test url bu req.body is empty.
I'm using NodeJS, Express & the middleware BodyParser.
Here my code :
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.post('/test/json/', function(req, res, next) {
res.json(req.body);
})
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.listen(8282);
In my req.body, it should disply {username:"Yacine"}
Please help me figure out with this cause I read all post looks like my problem & all solution provided are already used in my code.
Thanks
You must declare middlewares before routes so you can use them, try to change like this:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,
Content-Type, Accept");
next();
});
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.post('/test/json/', function (req, res, next) {
res.json(req.body);
});
app.listen(8282);
const express = require("express"),
http = require("http"),
bodyParser = require("body-parser"),
cookieParser = require('cookie-parser'),
session = require('express-session'),
morgan = require('morgan'),
methodOverride = require('method-override'),
compression = require('compression');
const app = express();
// compress responses
app.use(compression());
process.on('uncaughtException', function(exception) {
console.log(exception);
});
const config = require("./app/config.js")();
const logger = require("./app/server/modules/logger");
//app Config.
app.use(methodOverride());
app.set('env', 'dev');
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
//cross domain
app.use(function(req, res, next) {
if (req.method === 'OPTIONS') {
var headers = {};
headers["Access-Control-Allow-Origin"] = "*";
headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
headers["Access-Control-Allow-Credentials"] = false;
headers["Access-Control-Max-Age"] = '86400'; // 24 hours
headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";
res.writeHead(200, headers);
res.end();
}
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
res.header["Access-Control-Allow-Credentials"] = false;
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,X-HTTP-Method-Override, Content-Type, Accept");
next();
});
app.use(cookieParser());
app.use(session({ secret: 'xxxxxxxxxxx' }));
// app.use(cookieParser('optional secret string'));
// app.use(session({secret: 'xxxxxxxxxxx'}));
app.locals.pretty = true;
//Folder config.
/*app.use(express.static(__dirname + '/app/user/'));*/
app.use('/', express.static(__dirname + '/app/user/'));
app.use('/admin', express.static(__dirname + '/app/admin/'));
require('./app/server/router')(app); //route file
// catch 404 and forward to error handler
app.use(function(req, res, next) {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
if (app.get('env') === 'dev') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.json({
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error.html', {
message: err.message,
error: {}
});
});
http.createServer(app).listen(config.port, function(err) {
if (err) console.log(err);
logger.info("server listening on port " + config.port + " in " +
config.mode + " mode");
});
this is my http link http://localhost:9989/ later it will redirected to http://localhost:9989/login for the first time it works fine , when i refresh http://localhost:9989/login its says {"message":"Not Found","error":{"status":404}}, why its happening ? is there any solution for this ? or did i any mistake ? please guide me here!!
I would like to sue a middleware just for the /doc path so it can serve satic file and have a basic auth.
But when i try to get /doc i have a cannot get /doc error.
Does anyone have any idea ?
var app = express();
app.use(bodyParser.urlencoded({ extended: true })); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()) ; // parse application/json
app.use(functio //app.use('/doc', express.static('./doc'));n(req, res, next) {
res.header("X-powered-by", "NodeJs");
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,Authorization");
next();
});
app.use(function(req, res, next) {
console.log(' - ',req.originalUrl);
next();
});
var router = express.Router();
router.use(express.basicAuth('testUser', 'testPass'));
router.get('/doc', function(req, res, next) {
console.log("inside doc");
express.static('./doc');
next();
});
app.use('/conf',require('./v1/data_config'));
thanks and regard
2 Things:
You have to add your router to your express app and you should move the '/doc' route outside of your router as authentication could interfere with your app.
var router = express.Router();
router.use(express.basicAuth('testUser', 'testPass'));
router.get('/', express.static('doc'));
app.use('/doc',router);
I have an app that I'm trying to make into an API with lambda and claudia. I'm getting 'Error: 'app.router' is deprecated' even after I remove the line app.use(app.router) which is what the docs say: https://github.com/expressjs/express/wiki/Migrating-from-3.x-to-4.x
here is my server.js code: (i removed any adding of paths and it still gives me that error)
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(favicon(path.join(__dirname, 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static('assets'));
app.use(enableCors);
// catch 404 and forward to error handler
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
function enableCors(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
}
module.exports = app;
Could this have something to do with caching? Are there any other methods that I need to update in order to satisfy the 'app.router deprecated' call?
I am building a Node API on express which takes GET requests and uses the parameters supplied by the client to return the results of GET requests made to other API's.
In order to keep the controller thin when adding more API's I would like to export the logic within the controller into a separate .js file, and module.export those functions back in, to be used in the controller. The problem here is that the functions that are being exported do not appear to be visible within the controller.
Pasted below is before and after code to illustrate progress made so far.
app.js (before) - see router.get('/')
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 request = require('request');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
var router = express.Router();
if ( app.get('env') === 'development') {
var dotenv = require('dotenv');
dotenv.load();
};
var prodAdv = require('./lib/prod-adv.js')
// 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(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/api', router);
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
router.get('/', function(req, res) {
request('https://openapi.etsy.com/v2/listings/active?includes=Images&keywords=' + req.param('SearchIndex') + '&limit=100&api_key=' + process.env.ETSY_KEY, function(error, response, body) {
res.header({'Access-Control-Allow-Origin': '*'});
var data = JSON.parse(body);
res.json(data);
});
});
router.use('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, accept, authorization");
next();
});
var server = app.listen(9876, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s',host,port);
});
module.exports = app;
This approach works, returning JSON objects. However the following approach to try and export the code does not work.
apiCaller.js
var express = require('express');
var app = express();
if ( app.get('env') === 'development' ) { var dotenv = require('dotenv'); dotenv.load(); };
var request = require('request');
var call, response;
var call = function(searchIndex) {
return request('https://openapi.etsy.com/v2/listings/active?includes=Images&keywords=' + searchIndex + '&limit=100&api_key=' + process.env.ETSY_KEY, function(error, response, body) {
response = JSON.parse(body);
});
};
module.exports.response = response;
module.exports.call = call;
app.js (after)
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 squid = require('./lib/apiCaller.js');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
var router = express.Router();
if ( app.get('env') === 'development') {
var dotenv = require('dotenv');
dotenv.load();
};
var prodAdv = require('./lib/prod-adv.js')
// 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(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/api', router);
// 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 handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
router.get('/', function(req, res) {
squid.call(req.param('SearchIndex'));
res.header({'Access-Control-Allow-Origin': '*'});
res.json(squid.response);
});
router.use('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, accept, authorization");
next();
});
var server = app.listen(9876, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s',host,port);
});
module.exports = app;
What occurs now in the browser is a 200 OK with an empty response body. console.logging the responses return undefined objects.
You need to rewrite your call function to have a callback since request(...) is asyncronous
var call = function(searchIndex, callback) {
request('https://openapi.etsy.com/v2/listings/active?includes=Images&keywords=' + searchIndex + '&limit=100&api_key=' + process.env.ETSY_KEY, function(error, response, body) {
if (!error && response.statusCode == 200) {
return callback(null, JSON.parse(body));
}
callback('error');
});
};
Only export call function, there's no need to export or even use response and no need for this line
var call, response;
Now you also need to use it a bit different way
router.get('/', function(req, res) {
res.header({'Access-Control-Allow-Origin': '*'});
squid.call(req.param('SearchIndex'), function(err, data){
if(!err) return res.json(data);
res.json({error: err});
});
});