I am trying to make an app using Instagram's real-time api. I want to use Firebase to host my server. Below is my folder structure:
-main.js (instagram get and post requests here)
-server.js (setup express server here)
-firebase.json
-public (all firebase files)
--index.html
--scripts
--styles
I first make my subscription to Instagram by typing this in my command line:
curl -F 'client_id=7be53c459291486ead4916048ac434ad' \
-F 'client_secret=88ad262f9e57481bbf1ea7312d179a50' \
-F 'object=tag' \
-F 'aspect=media' \
-F 'object_id=turtles' \
-F 'callback_url=https://instagram-slideshow.firebaseapp.com/callback' \
https://api.instagram.com/v1/subscriptions/
I get an invalid response when I make the subscription request. Where should I put my server code? In my public folder? I cannot find any examples on how to use firebase to host your server. Can someone show me an example?
This is my server.js code:
var express = require('express');
var app = express();
require('./app.js')(app);
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
And this is my main.js
module.exports = function(app){
// when instagram tries to GET my URL, I need to return the hub.challenge and hub.verify_token
app.get('/callback', function (req, res) {
res.send('Hello World!');
if(req.param("hub.verify_token") == "myVerifyToken") {
res.send(req.param("hub.challenge"));
}
else {
res.status(500).json({err: "Verify token incorrect"});
}
});
// when instagram sends a post request to my server, check for updates on my end
app.post('/', function (req, res) {
res.send('POST request to the homepage');
});
}
Related
I'm trying to learn nodejs and express and i created a simple server. I want to run some JS code for response.
When I used this method it's works.
const express = require('express');
const path = require('path');
require('dotenv').config();
const app = express();
const port = process.env.PORT || "8000";
app.get('/', (req, res) => {
res.send(`<script>
console.log("Program works!");
</script>`);
});
app.listen(port, () => {
console.log(`Listening to requests on http://localhost:${port}`);
});
But writing JS as String is hard so I tried this:
const express = require('express');
const path = require('path');
require('dotenv').config();
const app = express();
const port = process.env.PORT || "8000";
app.get('/', (req, res) => {
res.send(`<script src="./response.js"></script>`);
});
app.listen(port, () => {
console.log(`Listening to requests on http://localhost:${port}`);
});
And i get this error:
GET http://localhost:8000/response.js net::ERR_ABORTED 404 (Not Found)
When you send this:
<script src="./response.js"></script>
to the browser, the browser will parse that and see the src attribute and will then immediately request ./response.js from your server. But your server doesn't have any route to respond to that request (thus it gets a 404 error back from your server). Remember that a nodejs server serves NO files by default (unlike some other web servers). So, you have to create routes or middleware for anything that you want it to serve.
So, you need to add a route to your server that will response to a request for response.js. First change your <script> tag to this:
<script src="/response.js"></script>
You want the request to be "path absolute" so it does not depend upon the path of the containing page. Then, you need to add a route handler for response.js to your server.
This can be done as a single route:
app.get('/response.js', (req, res) => {
res.sendFile("response.js", {root: __dirname});
});
Or, you can use express.static() to serve a whole directory of publicly available files with one line of code (if you also move all publicly available static files to their own directory away from your server files).
I am working in MEAN STACK application, I face one issue in a live site.
In my live web site, I have stop Apache server and run nodeJs by using pm2.
Once nodeJs started by pm2, my site running very well, but after every next day, Apache server automatically starts and my nodeJs site stop.
After stopping of Apache server the nodeJS works fine.
app.js
"use strict";
var logger = require("./config/log");
var express = require("express");
var https = require('https');
var http = require("http");
var fs = require('fs');
var app = express();
var exec = require('child_process').exec;
var config, hostName, sslOptions, httpServer, callSocketDir;
/**
* #description all process variables
*/
require("./config/vars")(app, fs);
config = require("./config/config.js")(app, express);
callSocketDir = './socket';
sslOptions = {
key: fs.readFileSync(global.hzConfig.privateKey),
cert: fs.readFileSync(global.hzConfig.certificate),
passphrase: global.hzConfig.passPhrase
};
httpServer = https.createServer(sslOptions, app).listen(global.hzConfig.port,function (req, res) {
logger.log("info", 'my site is listening on ssl port ' + global.hzConfig.port + ", proccess id is " + process.pid + '!');
initEmailServer();
});
require(callSocketDir)(app, httpServer);
Stop apache server
/usr/local/apache/bin/apachectl stop
Start nodejs server
pm2 start httpsServer.js
dependencies
"express" => "version" : "4.13.4",
"nodeJs" => "version" : "v7.4.0",
"https" => "version" : "^1.0.0"
Please give me a proper guideline for this issue.
Basically the Apache server and nodejs server might be on the same port
for example
if node js server running on port 80 and your Apache server to port is also running port 80
try and set one of the server to port 8080
Hi I am currently trying to learn how to create a backend for my app but when trying to create a port 3000 and having curl it produces this error:
NodeTutorial git:(master) ✗ curl -v http://localhost:3000 - the connection is refused.
Please Help.
My code in my index.js is as follows:
var http = require('http'),
express = require('express');
var app = express();
app.set('port', process.env.PORT || 3000);
app.get('/', function (req, res) {
res.send('<html><body><h1>Hello World</h1></body></html>');
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Seems your server has not started, try running below steps and see if you are able to connect or not:
Step 1: Create a directory which will contain all the files related to our app and execute npm init:
$ mkdir nodejs-server
$ npm init
Step 2: Install Express as a dependency:
$ cd nodejs-server
$ npm install --save express
Step 3: Create default entry point for Node.js i.e index.js, inside the same directory we created:
$ cd nodejs-server
$ touch index.js
Copy the content you have shown in your question in index.js:
var http = require('http'),
express = require('express');
var app = express();
app.set('port', process.env.PORT || 3000);
app.get('/', function (req, res) {
res.send('<html><body><h1>Hello World</h1></body></html>');
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Step 4: Move to directory nodejs-server and start the app following below command:
$ cd nodejs-server
$ node index.js
I am currently trying to learn how to use the MEAN stack and I'm having trouble with executing POST requests on the server.
This is my server.js script.
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.get('/api/posts', function(req, res) {
res.json([
{
username: 'dickeyxxx',
body: 'node rocks!'
}
]);
});
app.post('api/posts', function(req, res) {
console.log('post received!');
console.log(req.body.username);
console.log(req.body.body);
res.send(201);
});
app.listen(3000, function() {
console.log("Server listening on", 3000);
});
I tried sending request to the server using curl. GET requests work without a hitch but POST requests are giving me much trouble. This is my curl statement:
curl -v -H "Content-Type: application/json" -XPOST --data "{\"username\":\"dickeyxxx\",\"body\":\"node rules!\"}" http://localhost:3000/api/posts
I'm getting HTTP 404 Not Found and CANNOT POST /api/posts
I've tried restarting my server.js script but to no avail.
How do I solve this problem? Thank you for your help.
You are missing forward slash at the beginning for POST. Try
app.post('/api/posts', function(req, res) {
res.send(201);
});
How do I GET a JSON file with express.js? I want to be able to access it in my Mac terminal. I'm working on a college assignment that asks me to write an HTTP server that will act as a simple data store. It must respond to GET, PUT, POST, and DELETE requests. I must use express.js instead of fs for this app.
So far, in my root directory I have a server.js file and I have a subdirectory called lib that holds another subdirectory called notes. Notes is where the JSON files will live.
In my root directory, I have a server.js file. This is all I have so far:
'use strict'
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var notes = './lib/notes';
app.use(bodyParser.json());
app.get('/', function(req, res) {
//
//this is the part I need help with
//
}
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log('Server started on port ' + port;
});
Once I have this GET request working, from my Mac terminal I should be able to send a GET request and receive all JSON files inside the notes directory.
...from my Mac terminal I should be able to send a GET request and
receive all JSON files inside the notes directory.
Provided you do not want to use fs module(well you dont need one either),
you can simply set a route for GET requests and send the json file in response with app.sendFile()
app.get('/',function(req,res){
res.sendFile(path.normalize(__dirname + '/foo.json'))
//assuming your app.js and json file are at same level.
//You may change this to 'lib/notes/foo.json' to fit you case
})
path is a module that you would need to require().
__dirname is the directory that the currently executing script is in.
and finally foo.json is the file containing your json
{
"name":"nalin",
"origin":"stackoverflow"
}
Here's the complete code for app.js
var express = require('express');
var path = require('path');
var app = express();
app.get('/',function(req,res){
res.sendFile(path.normalize(__dirname + '/foo.json'))
})
app.listen(3000);
Which will help you run the node server with node app.js.
Finally you can access the json with by
visiting http://localhost:3000/ on your browser
by running curl command on your mac terminal curl localhost:3000
Hope this helps.
You can serve your .json files as static:
app.use('/notes', express.static( notes ));
http://expressjs.com/starter/static-files.html
Or you can do it manually width path pattern:
app.get('/notes/:file', function(req, res) {
fs.readFile(notes + "/" + req.params.file, function(err, data) {
if(err) {
res.status(404).send('Not found');
} else {
res.contentType(req.params.file);
res.send(data);
}
res.end();
});
});