Disable CORS in ExpressJS - node.js

I have two nodeJS/express applications. For simplicity, I'll say one is hosted on www.example1.com and the other is hosted on www.example2.com. I want to send a POST request from www.example2.com to wwww.example1.com. I do this with the following code:
<form action="www.example1.com" method="POST">
<input type="text" name="name"></input>
<input type="submit" value="Submit"></input>
</form>
I only want this to accept requests from www.example1.com. How do I do this? Also, currently, when I do this post request, the POST request is actually going through. I don't understand why. Are there no default settings to prevent against the cross domain requests? How can I put up these settings.
Any help would be greatly appreciated!
Thanks!

the cors middleware package is the standard way to do this
https://www.npmjs.com/package/cors
e.g:
const allowedOrigins = ['www.example1.com',
'www.example2.com'];
app.use(cors({
origin: function(origin, callback){
if(!origin) return callback(null, true);
if(allowedOrigins.indexOf(origin) === -1){
const msg = 'The CORS policy for this site does not allow access from the specified Origin.';
return callback(new Error(msg), false);
}
return callback(null, true);
}
}));

Related

Cannot POST /addfriend error using Express

I am trying to create a simple form handler using express. Here is a similar question but I can't related it with my problem. I have written all of my file Here anyone can check it by using all of my file. For better understanding I copy my code here:
app.js code:
const express = require('express');
const app = express();
//routes
app.get('/',function(req,res){
res.send('This is root dir');
});
app.get('/friends',function(req,res){
var friends=['sakib','emon','rayhan'];
res.render('friends.ejs',{friends:friends});
});
app.get('/addfriend',function(req,res){
res.send('ADD friend page launch!!!!!');
});
app.listen(3000,function(){
console.log("server has started on port 3000!!!");
});
ejs(friends.ejs) code:
<h1>Here is list of your Friend:</h1>
<%friends.forEach(function(friend){%>
<li><%=friend%></li>
<%});%>
<form action="/addfriend" method="POST">
<input type="text" name="friend" placeholder="name">
<button>
Submit
</button>
</form>
When I type any name in the input box and clicked Submit it didn't post to /addfriend. I didn't understand where is my problem. Please goto input box(link) after started the server.
For better understand what's my actual problem is then please use goorm IDE(shared file) where I uploaded everything.
You are using get request instead of post for addfriend.
app.post('/addfriend',function(req,res){
console.log("I'm called wohoo!");
res.send('ADD friend page launch!!!!!');
});

Upload Files using Express + Connect (Node)

I'm trying to upload files via a web site. As I'm new in web programming, I didn't found a full example in web that solves all my doubts.
My scenario is:
Nodejs (v.0.10.25) + Express (4.9.0)
Trying to use Connect (3.0).
I created my app using the Express command. So the app.js was created default. I figured out that Express doesn't have multipart by default. And I should install a middleware to use it.
I'm trying to install Connect. The question is: How do I configure it? Must I have to replace the Express server for Connect server or it can exist together ?
Some one can explain how does it works ? Or show an example ?
Thanks too much!
via http://howtonode.org/really-simple-file-uploads
<!-- client html -->
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file_upload">
</form>
// node.js server
var fs = require('fs'),
http = require('http');
app = (require('express'))();
app.post('upload', function(req, res){
fs.readFile(req.files.file_upload.path, function (err, data) {
var newPath = __dirname + "/uploads/uploadedFileName";
fs.writeFile(newPath, data, function (err) {
res.redirect("back");
});
});
});

Get ng-model values on POST to Express.js endpoint

I am creating a Node.js application with AngularJS.
I want to make a simple POST, using Angular. This POST should post a couple of values to my server, where I can see them using console.log.
In my HTML code, I build it with the ng-model and a button that has a ng-click.
I can tell my Node.js server is being hit, as it outputs the post called in the console.
However, I have been trying to read about how to read the POST values, but I haven't found a solution.
How would I modify my code to read serialKey and gameTitle in my Express.js endpoint?
My HTML code:
<div class="input-group" ng-controller="CreateController">
<p>Serial key:<br/>
<input class="form-control" ng-model="serialKey" />
</p>
<p>Game:<br/>
<input class="form-control" ng-model="gameTitle" />
</p>
<span class="input-group-btn">
<button class="btn btn-default"
ng-click="postNewIsbn(serialKey,gameTitle)">Add</button>
</span>
</div>
Angular controller code:
app.controller('CreateController',function($scope, $http) {
var url = '/api/serials';
$scope.postNewIsbn = function(serial, game) {
$http.post(url, {
serial: serial,
gametitle: game
})
.success(function (data) {
$scope.data.status = 'success';
})
.error(function(error) {
$scope.data.error = error;
});
};
});
Express.js endpoint
app.post('/api/serials',function(req,res){
console.log(req.body);
console.log('post called');
});
It appears to be the problem of setting content-type header. In your angular application you can set defaultHeaders for your post request just after you initialize the module or in your config function with this line
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
Do remember to inject the $httpProvider dependency whereever you setting this header
UPDATE
It may be the case that you need to configure your express in order to use the bodyParser with this line:
app.use(express.bodyParser());
req.param(name)
When attempting to retrieve data passed with the request, the req.param() function checks the following in order to find the parameter:
req.params
req.body
req.query
See the docs here.
Also, try explicitly setting the content-type header in the POST request to "application/json".

CSRF token not working when submitting form in express

i'm trying to get forms working in my express app. i have a middleware function that passes the csrf token, req.session._csrf, to res.locals.csrf_token, so the view can use it. now i'm trying to use the local variable in my view and i'm getting a forbidden error from my session middleware.
here's my form code - i'm using handlebars as my templating engine:
<form method='post' action='/api/entries' enctype='multipart/form-data' >
<input type='hidden' name='_csrf' value={{csrf_token}} />
<input class='foo' type='text' />
<input class='bar' type='text' />
<button id='submit' type='submit'> SUBMIT
</form>
i've tried referencing the csrf_token variable with and without the double curly braces and neither works. any ideas on what i am doing wrong? the Error: Forbidden happens before my route function for POSTing to /api/entries is even called. so i'm pretty sure the problem is that i'm doing something wrong with referencing the csrf token..
*edit:*in regards to the "req.session._csrf is deprecated, use req.csrfToken() instead" getting logged to the console, i did:
grep -r '_csrf' .
in my app directory. here was the output.. it doesn't look like i'm referencing it anywhere besides the view, where my hidden CSRF field is named "_csrf"..
./node_modules/express/node_modules/connect/lib/middleware/csrf.js: var secret = req.session._csrfSecret;
./node_modules/express/node_modules/connect/lib/middleware/csrf.js: req.session._csrfSecret = secret;
./node_modules/express/node_modules/connect/lib/middleware/csrf.js: Object.defineProperty(req.session, '_csrf', {
./node_modules/express/node_modules/connect/lib/middleware/csrf.js: console.warn('req.session._csrf is deprecated, use req.csrfToken() instead');
./node_modules/express/node_modules/connect/lib/middleware/csrf.js: return (req.body && req.body._csrf)
./node_modules/express/node_modules/connect/lib/middleware/csrf.js: || (req.query && req.query._csrf)
./v/home.hbs: <input type='hidden' name='_csrf' value={{csrf_token}} />
./v/show.hbs: <input type='hidden' name='_csrf' value={{csrf_token}} />
here is the entire error stack i'm getting when trying to POST to the /api/entries endpoint (i stupidly neglected to mention this before, but i'm using connect-redis for session middleware):
Error: Forbidden
at Object.exports.error (appFolder/node_modules/express/node_modules/connect/lib/utils.js:63:13)
at createToken (appFolder/node_modules/express/node_modules/connect/lib/middleware/csrf.js:82:55)
at Object.handle (appFolder/node_modules/express/node_modules/connect/lib/middleware/csrf.js:48:24)
at next (appFolder/node_modules/express/node_modules/connect/lib/proto.js:193:15)
at next (appFolder/node_modules/express/node_modules/connect/lib/middleware/session.js:318:9)
at appFolder/node_modules/express/node_modules/connect/lib/middleware/session.js:342:9
at appFolder/node_modules/connect-redis/lib/connect-redis.js:101:14
at try_callback (appFolder/node_modules/redis/index.js:580:9)
at RedisClient.return_reply (appFolder/node_modules/redis/index.js:670:13)
at ReplyParser.<anonymous> (appFolder/node_modules/redis/index.js:312:14)
edit 2: the error in connect-redis.js is a function trying to get the current session by the session ID and failing. don't know why this would be happening, my connect-redis setup looks correct. this is killing me
EDIT: If you don't need file uploads, don't use the multipart/form-data enctype. Switching to the default enctype would allow express.csrf() to parse the _csrf token.
In order to parse forms with the multipart/form-data enctype, you need use a multipart parser in your app configuration, or handle file uploads yourself. It's recommended to avoid using the included express.bodyParser() and instead use something like busboy or formidable on the routes you're expecting file uploads, to prevent an exploit.
If you go this route, your _csrf field will no longer be caught by express.csrf() because the form body will not be parsed until after the request passes that middleware. Set your form action to '/api/entries?_csrf={{csrf_token}}' to get around this.
var fs = require('fs');
var async = require('async');
var express = require('express');
var formidable = require('formidable');
var app = express();
app.use(express.urlencoded())
.use(express.json())
.use(express.cookieParser())
.use(express.session())
.use(express.csrf())
app.get('/upload', function(req, res) {
// File uploads ignored.
res.render('upload', {_csrf:req.csrfToken()});
});
app.post('/upload', function(req, res) {
// Explicitly handle uploads
var form = new formidable.IncomingForm();
form.uploadDir = 'temp';
var count = 0;
var maxAllowed = 10;
form.onPart = function(part) {
if (!part.filename) return form.handlePart(part);
count++;
// Ignore any more files.
if (count > maxAllowed) return part.resume();
form.handlePart(part);
};
form.parse(req, function(err, fields, files) {
// Process the files. If you don't need them, delete them.
// Note that you should still reap your temp directory on occasion.
async.map(Object.keys(files), function(key, cb) {
fs.unlink(files[key].path, cb);
}, function(err) {
res.end();
});
});
});
CSRF syntax has changed slightly in the latest versions of Express/Connect. You now want your middleware to look like this:
.use(express.csrf())
.use(function (req, res, next) {
res.cookie('XSRF-TOKEN', req.csrfToken());
res.locals.csrftoken = req.csrfToken();
next();
})
For testing your code, note that you first need to GET the form page in order to generate the CSRF token. Only then will your POST succeed. If it fails, you need to reload the page in the browser before trying to POST again.
I too hit this problem today and it's taken several hours for me to find a solution. Hopefully this answer helps someone with my exact problem. As #amagumori, I'm using redis for session handling and express 3.4.8, connect-redis 1.4.7.
Basically I was able to determine that the order of my express configuration affects the number of times a new token was issued. It seemed like everything being served out of public was creating a new token.
Specifically in my case I had to move the calls
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(express.static(__dirname + '/public'));
above
app.use(express.csrf());
app.use(function(req, res, next){
res.locals.token = req.csrfToken();
next();
});
and tokens are issued as expected for sessions.

Express cannot PUT/DELETE method. What is going wrong?

Ok So I have a simple node.js / express.js / mongodb app set up here with my config as follows.
var express = require('express'),
mongoose = require('mongoose');
http = require('http');
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
//middleware stack
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + "/public"));
});
mongoose.connect("mongodb://localhost/hello");
The problem lies when I try to make PUT or DELETE requests. My form is this simple
<form method="POST" action="/users/#{user.name}">
<input type="hidden" name="_method" value="PUT"/>
</form>
Now my router catches the route with the express .put() method
app.put('/users/:name', function(req, res) {
var b = req.body;
Users.update(
{ name: req.user.name },
{ name: b.name, age: b.age, email: b.email },
function(err) {
res.redirect('/users/'+b.name);
});
})
When I make the request I simply get a "Cannot PUT" or "Cannot DELETE" error.
I have tried to make this same request via chomes RESTful client with the same result.
I have read a topic witch has the same problem as me although following the comments the answers did not solve my problem.
Questions I have looked into
expressjs support for method delete and put without the methodoverride
Are the PUT, DELETE, HEAD, etc methods available in most web browsers?
Along with a few others.
I have also referenced the express.js and mongo documentation several times.
I just cant think what could be going wrong.
Any help is appreciated.
Update
As Jonathan Lonowski pointed out PUT can also be used, so you can ignore my old answer.
Getting Cannot PUT or Cannot POST errors, means your callback is not executing successfully. My guess is that Users.update is failing, which is why it cannot POST or PUT. Can you check it.
Old answer
Try changing this line
app.put('/users/:name', function(req, res) {
to
app.post('/users/:name', function(req, res) {
since you are trying to submit the form
Is the <form> you listed in a view or a static file under __dirname + "/public"?
Within a static file, the #{user.name} probably isn't being replaced with the user's name and will be treated as a URL Fragment.
The <form> will actually submit to /users/ rather than /users/:name since that's the path:
console.log(url.parse('/users/#{user.name}'));
{ hash: '#{user.name}',
pathname: '/users/',
path: '/users/',
href: '/users/#{user.name}' }
The <form> should be generated from a view if it isn't since the action needs to be dynamic and data-driven. With Jade and assuming user is a member of locals, that would be:
form(method='POST', action='/users/' + user.name)
input(type='hidden', name='_method', value='PUT')
Unless there is strange magic at work, your form makes a POST request, not a PUT. If you want to PUT, I would suggest using the jQuery.ajax function with a type: 'PUT' parameter, like this answer, from a form handler, see jQuery.submit. Don't forget to return false so that the form doesn't submit twice.
If your using method override, make sure you have declared it before you use your routes. That was the problem I was having.
app.post("/movies/:id") is one solution.
If you still want to use app.put("/movies/:id") then try this:
Install method-ovveride from npm.
Require it in your app.js file.
Open the form from where you wanna invoke PUT request
make sure your form has the following attributes:
action="/movies/<%= movies._id %>?_method=PUT " method="POST" >
These two solutions worked for me. If you are following REST, then use the method-ovveride else app.post() will also do the trick
Change res.redirect('path') to res.redirect(303, 'path')
In Put and Delete, if you want to redirect to get address, you should pass 303 as first parameter. (source)
one solution is to use cors middleware for you PUT,PATCH and DELETE requests like this in your app.js file like this:
first install the cors package via npm :
npm i cors
then add the following code to your app.js:
const cors = require('cors')
app.use(cors())

Resources