I got this error when I try to deploy node.js files.
Updated failed with Could not triggers. The error was Error: Module body-parser.js not found
Here is my code:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.set('views', 'cloud/views');
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
app.get('/hello', function(req, res) {
res.render('hello', { message: 'Congrats, you just set up your app!' });
});
app.listen();
I have npm install body-parser in my local machine. What should I do in order for Parse to recognize this module?
Parse's express framework is not a full node.js app. So you cannot directly use node.js packages that aren't supported by Parse.
Try this one instead,
var express = require('express');
var app = express();
app.set('views', 'cloud/views');
app.set('view engine', 'ejs');
app.use(express.json()); // to support JSON-encoded bodies
app.use(express.urlencoded()); // to support URL-encoded bodies
app.get('/hello', function(req, res) {
res.render('hello', { message: 'Congrats, you just set up your app!' });
});
app.listen();
Reference Docs # Parse.com
Related
I'm trying to set up a socket.io connection on Cloud Foundry via IBM Toolchains. I've gone through the docs and have been trying to get socket.io to connect to port 4443. I'm kind of new to this so would appreciate if you could provide some pointers on how to set up socket.io on the CF env as I still struggle to digest parts of the documentation. Code can be found below.
//---------------------------
// app.js
//---------------------------
// Start the app on cloud foundry
var express = require('express');
var app = express();
var cfenv = require('cfenv');
var appEnv = cfenv.getAppEnv();
app.use(express.static(__dirname + '/public'));
app.listen(appEnv.port, '0.0.0.0', function() {
console.log("Server is starting on " + appEnv.url);
});
// Connect socket.io
var server = require('http').Server(app);
var io = require('socket.io')(server);
var cookieParser = require('cookie-parser');
app.get('/', function (req, res) {
res.sendFile(__dirname + 'public/index.html');
});
io.on('connection', function (socket) {
console.log('a user connected');
});
var port = 4443; // Cloud Foundry assigned port for TCP/WebSocket communications
server.listen(port, function() {
console.log('listening on ', port);
});
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect("https://0.0.0.0:4443");
</script>
My understanding after going through the socket.io docs is that the IP provided should be the location.hostname which I believe to be 0.0.0.0 in this case as it refers to the IP which the express instance for the app is listening on. Not too sure about this though.
By changing it to below:
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.slim.js"></script>
<script> var socket = io(); </script>
The error changes to a 404 error with the following error being repeated: "https://realtimetrafficanalysisaks.mybluemix.net/socket.io/?EIO=3&transport=polling&t=". I've checked regarding the app and server settings but can't seem to pinpoint the error
Thanks in advance!
I didn't manage to sort this out with socket.io due to the port issue but I was able to get it running using the express-ws package
I'm trying to connect to a local dev environment via an IP address. I'm getting an error because HTTPBatchedNetworkInterface shows:
_uri: "http://10.0.1.10/graphql"
...when it needs to be:
"http://10.0.1.10:3000/graphql"
Here's my server-side setup code:
const localHostString = '10.0.1.10';
const METEOR_PORT = 3000;
const GRAPHQL_PORT = 4000;
const server = express();
server.use('*', cors({ origin: `http://${localHostString}:${METEOR_PORT}` }));
server.use('/graphql', bodyParser.json(), graphqlExpress({
schema,
context
}));
server.use('/graphiql', graphiqlExpress({
endpointURL: '/graphql',
subscriptionsEndpoint: `ws://${localHostString}:${GRAPHQL_PORT}/subscriptions`
}));
// Wrap the Express server
const ws = createServer(server);
ws.listen(GRAPHQL_PORT, () => {
console.log(`GraphQL Server is now running on http://${localHostString}:${GRAPHQL_PORT}`);
console.log(`GraphiQL available at http://${localHostString}:${GRAPHQL_PORT}/graphiql`);
// Set up the WebSocket for handling GraphQL subscriptions
new SubscriptionServer({
execute,
subscribe,
schema
}, {
server: ws,
path: '/subscriptions',
});
});
What is the correct way to get the port number into HTTPBatchedNetworkInterface._uri?
Thanks in advance to all for any info.
Fixed. My framework is Meteor and I had to set ROOT_URL = 10.0.1.10:3000/.
When I run node app.js myself, I do not get a CORS error in the browser. When I run it as a service, I do not get the error on the OPTIONS request, but I do get the error on the POST request.
I created the service using nssm. I configured the service to log in with the same account I use to run the node process.
var express = require('express');
// The `socket` module initializes socket.io for other endpoints
var io = require('./modules/socket');
var upload = require('./routes/upload');
var app = express();
app.configure(function () {
app.use(express.cookieParser());
app.use(express.session({secret: 'secret', key: 'express.sid'}));
});
app.set('port', 5000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.all('/up', function(req, res, next) {
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', 'https://####.###');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
if (req.method == "OPTIONS") {
res.send(200);
} else {
next();
}
});
app.post('/up', upload.upload);
Can you think of a reason why the error on POST will only occur when it is running as a service?
Found the problem. When creating the service with NSSM, the Startup Directory needed to be the location of the app's main javascript file, not the node executable's location.
It looks like it was permissions problem when writing to disk.
I just changed my server to use HTTPS. I have a very boiler plate code. When I go to localhost:8888, the browser hangs and my route never gets called. Curl from the command line is the same.
I am wondering I am defining my route incorrectly.
THe code is the following:
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var https = require('https');
var path = require('path');
var app = express();
var fs = require('fs');
// all environments
app.set('port', process.env.PORT || 8888);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.methodOverride());
app.use(app.router);
//app.use(logErrors);
app.use(express.static(path.join(__dirname, 'public')));
var options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')};
app.get('/', routes.index);
app.get('/users', user.list);
https.createServer(options, app.handle).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Anyone sees what the issue is?
I think you want just app where you have app.handle:
https.createServer(options, app)....
Also note for cURL testing you'll need to do curl --insecure https://localhost:8888 since you are presumably using a non-commercial self-signed certificate which neither curl nor browsers will trust without a user explicit override.
You need to go to https://localhost:8888.
The browser can't automatically figure out that you're listening for SSL connections on that port.
I'm trying establish an AJAX connection on node 0.10.3 using mootools. My code is:
Client
var ajax = new Request({
url: '/register',
method: 'post',
onSuccess: function(responseText){
console.log(responseText);
}
})
var json = {data:'data'};
ajax.send(JSON.stringify(json));
//ajax.send(json);
Server
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(1344);
app.post('/register', function(req,res){
//Auth.register()
console.log(req.body);
res.contentType('json');
res.send({ some: JSON.stringify({response:'json'}) })
})
The connection is working Ok. On the client I get the response. So the console.log(responseText) inside the OnSucces method is printing the correct value.
But on the server side, the console.log(req.body) is undefined.
I have a few doubts here. Does mootools converts the javascript object to a json string? Is it necessary to convert de object at all? What is the correct way of sending information trough AJAX to node? Is this ajax.send(JSON.stringify(json)); OK? Or is it like this ajax.send(json);?
Do I need to specify the headers to be json?
Apart for solving the particular problem, it would be nice some article, o some feedback to definitely clarify this concepts around node.js.
EDIT
I'm going to post the correct code, for those who are facing a similar problem. Noah was right about the parser, but there is another detail, the parser is expecting for the key data. Luckily I was using data as example!
Client
var ajax = new Request({
url: '/register',
method: 'post',
onSuccess: function(responseText){
console.log(responseText); //Logs "some": "{\"response\":\"json\"}"
}
})
ajax.send({data:{ok:'OK'}});
Server
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.listen(1344);
app.post('/register', function(req,res){
console.log(req.body); //logs {ok:'OK'}
res.contentType('json');
res.send({ some: JSON.stringify({response:'json'}) })
})
In the code you posted you are missing the bodyParser middleware app.use(express.bodyParser().
After you add the bodyParser middleware you will be able to access req.body
var express = require('express');
var app = express();
app.use(express.bodyParser()
app.use(express.static(__dirname + '/public'));
app.use(app.router)