Express.js connecting to Twitter - javascript

I am trying to Oauth authenticate with Twitter, using Express.js and Grant on my Windows 7 machine. When I run node app.js in command line I get the following:
The question is why doesn't MADE IT HERE also get outputted in the console.
Also, what secret should I be putting in app.js where I currently have 'very secret'? Does this need to be my consumer secret or just any string?
I am using Xampp and when I want to run in my browser (Chrome) I direct to: http://dummy.com:3000/ and I get 'This webpage not available'. If I instead direct to http://localhost/xampp/phptest/lions/idk/run.html then I get a blank web page. Which should I be using?
I was trying to follow alongside this: https://scotch.io/tutorials/implement-oauth-into-your-express-koa-or-hapi-applications-using-grant#configure-express
Here are all of my files:
app.js
var express = require('express')
, logger = require('morgan')
, bodyParser = require('body-parser')
, cookieParser = require('cookie-parser')
, session = require('express-session');
var fs = require('fs');
var obj = JSON.parse(fs.readFileSync('./config.json', 'utf8'));
var Grant = require('grant-express')
, grant = new Grant(obj) ;
var app = express();
app.use(logger('dev'));
app.use(grant);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
app.use(session({
name: 'grant', secret: 'very secret',
saveUninitialized: true, resave: true
}));
app.get('/handle_twitter_callback', function (req, res) {
console.log('MADE IT HERE');
console.log(req.query);
res.end(JSON.stringify(req.query, null, 2));
});
app.listen(3000, function() {
//document.getElementById("holder").innerHTML="GOT HERE";
console.log('Express server listening on port ' + 3000);
});
config.json
{ "server": {
"protocol": "http",
"host": "dummy.com:3000"
},
"twitter":
{
"key": "myconsumerkey",
"secret": "myconsumersecret",
"callback": "/handle_twitter_callback"
}
}
package.json
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "node app.js"
},
"bin": "./",
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.13.2",
"cookie-parser": "^1.3.5",
"errorhandler": "^1.4.1",
"express": "^4.13.1",
"express-session": "^1.11.3",
"fs": "0.0.2",
"grant-express": "^3.3.3",
"jade": "^1.11.0",
"method-override": "^2.3.4",
"morgan": "^1.6.1",
"multer": "^0.1.8",
"serve-favicon": "^2.3.0"
}
}
run.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>run</title>
<meta name="author" content="stephen" />
<!-- Date: 2015-07-17 -->
</head>
<body>
<script src="app.js"> </script>
</body>
</html>

There's a few things to note here:
1) Its important to note that node.js is JavaScript as/on a server. If you're using node.js, you don't need xampp. Xampp is a server usually for running php. Node is creating a server itself, so you don't need to use xampp at all.
app.listen(3000, function() {
console.log('Express server listening on port ' + 3000);
});
Is your app.js file telling your server to run on port 3000. Just hit localhost:3000 to view whatever page you're serving from your app.js file.
2) If you're looking to print something out on your console, use console.log('something');, and you'll see it in the same console as your Express server... stuff. Note that you're using the server console, not your browser's console. It looks like you're trying with //document.getElementById("holder").innerHTML="GOT HERE"; to change stuff in the browser from you server file, which is probably not what you're looking to do. You'll need to include a file to be run client-side to manipulate dom stuff.
3)
app.get('/handle_twitter_callback', function (req, res) {
console.log('MADE IT HERE');
console.log(req.query);
res.end(JSON.stringify(req.query, null, 2));
});
You'll need to head to localhost:3000/handle_twitter_callback to reach that, and I believe you'll see what you're looking for.
I would suggest hitting a tutorial that explains node and express full through without anything extra to begin with, then trying OAuth stuff.

Related

My Strapi admin panel is now showing loading status indefinitely on localhost

This was not the case a few days ago, yesterday this randomly occurred after some changes were made as I had added a significant number of new Fields attributes to a specific Collection Type...
Ever since, my Strapi CMS NodeJS backend is randomly not loading anymore on my localhost, it shows an infinite loading status...
When I first go to my localhost:1337 this is what I get, it all works as it has been and has loaded properly:
However, when I click "Open the administration" button to access the Strapi admin panel I get directed to "http://localhost/admin" and get the following:
When I click on the admin error in the Network tab, it shows the following:
Normally, the "Open the administration" tab would redirect me to http://localhost:1337/admin however clearly this time it did not.
Now I try to access http://localhost:1337/admin and this is where I receive the seemingly infinite loading error...
The first (failed) fetch error (above the preflight error, as this is causing the preflight error), shows:
My server.js file is as follows:
module.exports = ({ env }) => ({
host: env('HOST', '0.0.0.0'),
port: env.int('PORT', 1337),
cron: { enabled: true },
url: env('URL', 'http://localhost'),
admin: {
auth: {
secret: env('ADMIN_JWT_SECRET', '9bf8cc74ab83590b280df0851beaec60'),
},
},
});
My package.json is as follows:
{
"name": "Strapi-Backend",
"private": true,
"version": "0.1.0",
"description": "The Strapi backend of a JAMstack e-commerce platform built for a Udemy course.",
"scripts": {
"develop": "strapi develop",
"start": "strapi start",
"build": "strapi build",
"strapi": "strapi"
},
"devDependencies": {},
"dependencies": {
"strapi": "3.6.8",
"strapi-admin": "3.6.8",
"strapi-connector-mongoose": "3.6.8",
"strapi-plugin-content-manager": "3.6.8",
"strapi-plugin-content-type-builder": "3.6.8",
"strapi-plugin-email": "3.6.8",
"strapi-plugin-graphql": "^3.6.8",
"strapi-plugin-upload": "3.6.8",
"strapi-plugin-users-permissions": "3.6.8",
"strapi-provider-email-sendgrid": "^3.6.8",
"strapi-provider-upload-aws-s3": "^3.6.8",
"strapi-utils": "3.6.8",
"stripe": "^8.135.0"
},
"author": {
"name": "Zachary Reece"
},
"strapi": {
"uuid": "5e0b8d89-62ac-4e4e-995b-08644071605b"
},
"engines": {
"node": ">=10.0.0",
"npm": ">=6.0.0"
},
"license": "MIT"
}
Change server.js and try:
module.exports = ({ env }) => {
const port = env('PORT', '1337');
const host = env('HOST', '0.0.0.0');
const url = env('URL', `http://localhost${port !== '80' ? ':'+port : ''}`);
const adminAuthSecret = env('ADMIN_JWT_SECRET', '9bf8cc74ab83590b280df0851beaec60');
return {
host, port, url,
cron: { enabled: true },
cors: { enabled: true, origin: ['*'] },
admin: {
auth: { secret: adminAuthSecret },
}
}
};

How to create basic Node.js project with materialwebcomponents?

I am relatively new to Node.js. This is a very simple program so far, meant to just test the incorporation of material-components-web. I followed the instructions step-by-step in the readme, and this is what I have so far:
package.json
{
"name": "hello-polymer", "version": "0.1.0",
"description": "Intro to Polymer", "main": "index.js",
"scripts": { "start": "node index.js" },
"author": "vcapra1", "license": "ISC",
"dependencies": { "#webcomponents/webcomponentsjs": "^2.0.2" }
}
index.js
http = require('http')
fs = require('fs')
http.createServer((request, response) => {
response.statusCode = 200
response.setHeader('Content-Type', 'text/html')
let filename = "./" + request.url
if (request.url.startsWith("/#")) {
filename = "./node_modules/" + request.url
} else if (request.url == "/") {
filename = "./index.html"
} else {
response.statusCode = 404;
response.end("404 Not Found");
}
fs.readFile(filename, (err, data) => {
console.log("Request: ", request.url);
response.end(data)
})
}).listen(3000)
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MWC Test</title>
<script src="#webcomponents/webcomponentsjs/webcomponents-loader.js"></script>
<script type="module" src="#material/mwc-icon/mwc-icon.js"></script>
</head>
<body>
Hello, World
<mwc-icon>sentiment_very_satisfied</mwc-icon>
</body>
</html>
Then I run the following command in the project folder:
polymer serve
I've also tried starting it with npm using:
npm start
Both commands allow me to go to the webpage at http://localhost:XXXX, but each time all I get is the text "Hello, World sentiment_very_satisfied", and the plain text stays there with no icon.
I'm not really sure what I'm missing. I find it strange that the script src attributes reference #webcomponents as a sibling folder while said folder is actually in the node_modules directory, so I tried changing that, but still no luck.
I got it working by running with
polymer serve --module-resolution=node --npm.
This tells polymer-cli to transform npm style references to relative references when serving files. Although it doesn't work for index.html for some reason, so relative paths are required there:
<script src="node_modules/#webcomponents/webcomponentsjs/webcomponents-loader.js"></script>
<script type="module" src="node_modules/#material/mwc-icon/mwc-icon.js"></script>
You can read more here https://www.polymer-project.org/blog/2018-03-23-polymer-3-latest-preview#packagenames

Electron build app doesnt start express server

I'm building an app and all works fine while I'm in developer mode. Everythink works as it should. But when I package my app with electron-builder, app opens but it doesnt start express server and app doesnt work properly.
Here is my package.json code
{
"name": "artros",
"version": "1.0.0",
"description": "Artros",
"author": "MC3",
"license": "ISC",
"main": "start.js",
"scripts": {
"pack": "build --dir",
"dist": "build"
},
"build": {
"appId": "com.artros.app",
"productName": "Artros",
"win": {
"target": "portable",
"icon": "build/icon.ico"
},
"mac": {
"target": "dmg"
}
},
"dependencies": {
"body-parser": "^1.18.3",
"ejs": "^2.5.7",
"electron-pdf-window": "^1.0.12",
"express": "^4.16.2",
"multer": "^1.3.0",
"nodemailer": "^4.6.4",
"path": "^0.12.7"
},
"devDependencies": {
"electron": "^1.8.2"
}
}
and here is my start.js code
const cluster = require('cluster');
if (cluster.isMaster) {
require('./main.js'); // your electron main file
cluster.fork();
} else {
require('./app.js'); // your server code
}
and my main.js code
var electron = require('electron');
var browserWindow = electron.BrowserWindow;
var app = electron.app;
app.on('ready', function(){
var appWindow;
//appWindow
appWindow = new browserWindow({
width:1120,
height:620,
webPreferences: {
plugins: true
},
icon: __dirname + '/public/icon/icon.png'
});
appWindow.loadURL('file://' +__dirname + '/public/prva.html');
//appWindow.webContents.openDevTools();
});
// close app after all windows are closed
app.on('window-all-closed', () => {
app.quit()
})
If anybody has any idea what is the problem, please post it. Thanks
I had something similar happen to me. The challenge was that if you use fork() the application path changes. So I would recommend that you check __dirname in all of your files especially the ones in your forked process (e. g. app.js). I wouldn't be surprised if some of them don't make sense anymore.
I found the solution. The problem really was in my app.js code. At one detination I needed to add (path.join(__dirname, './path/to/file')). Guys thanks for your help.

API Data Not Displaying in EJS File

I am trying to use AJAX to get the JSON data from an API to display on my EJS file in Node JS. However, it seems that nothing is being pulled from the API in the first place. How can I display data from an API to page in Node JS? I have been trying for hours to find a solution to this one. Here is what I've got so far.
**index.js**
var express = require('express');
var app = express();
var url = require('url');
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
// views is directory for all template files
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'ejs');
app.get('/', function(request, response) {
response.render('pages/index')
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
var http = require("http");
(function($) {
$(function() {
var status = $('#status');
getData();
function getData() {
// Get the data from the Walmart API
$.ajax({
url: "http://api.walmartlabs.com/v1/trends?format=json&apiKey=
{api_key}",
dataType: "jsonp",
success: function(data) {
//Show this data in the console
console.log(data);
//variable instantiation
var itemId = data['items']['itemId'];
var name = data['items']['name'];
var regularPrice = data['items']['msrp'];
var salePrice = data['items']['salePrice'];
//Place data in HTML
$("#productId").html(itemId);
$("#name").html(name);
$("#regularPrice").html(regularPrice);
$("#salePrice").html(salePrice);
}
});
}
**index.ejs**
<!DOCTYPE html>
<html>
<head>
<title>Store App</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<script type="application/json" src="/js/index.js"></script>
</head>
<body>
<h1>Store App</h1>
<p>Welcome to the Store Node site. Here, you will find hot products on the
Walmart website. You can also browse by category or search by product id or
name.</p>
<section class="item-container">
<h1 id="name"></h1>
<ul id="current_trends">
<li id="productId"></li>
<li id="regularPrice"></li>
<li id="salePrice"></li>
</ul>
</section>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js">
</script>
</body>
</html>
**package.json**
{
"name": "node-walmart",
"version": "1.0.0",
"description": "walmart web services",
"main": "index.js",
"dependencies": {
"express": "^4.16.3",
"ejs": "*"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/sample/node-sample.git"
},
"author": "sample",
"license": "MIT",
"bugs": {
"url": "https://github.com/sample/node-sample/issues"
},
"homepage": "https://github.com/sample/node-sample#readme"
}
Use EJS like this Node-Cheat
and then you can do it like:
app.get('/', function(req, res, next) {
//see message is passed to index.ejs and ejs will take care of rendering it
//so same way you can load your api data here like:
axios.get('http://api.walmartlabs.com/v1/trends?format=json&apiKey={api_key}')
.then(function (apiData) {
//now pass apiData to index.ejs to take care of it
res.render('index',{message:"Hello World!", apiData: apiData});
})
.catch(function (error) {
//render your error.ejs here
});
});
See axios docs here.
In case you want to use new syntax:
app.get('/', async (req, res, next) => {
//see message is passed to index.ejs and ejs will take care of rendering it
//so same way you can load your api data here like:
try {
const apiData = axios.get('http://api.walmartlabs.com/v1/trends?format=json&apiKey={api_key}');
//now pass apiData to index.ejs to take care of it
res.render('index',{message:"Hello World!", apiData: apiData});
}
catch (e){
//render your error.ejs here
}
});
It's don't work like that. You need to make the call in your API to render it on a page. IIFE don't work here as you used.

Having trouble getting a counter reset function to work using sockets in express

I have a project I am working on for a coding bootcamp. For the project I need to create a website that has a button that when pressed adds +1 to a counter and displays how many times the button has been pressed. The project also needs a reset button that when pressed resets the count back to zero.
I created the project and everything is working well except for the reset function. Whenever I press the reset button nothing happens. I have looked over the code and I don't see any errors in the reset function that I wrote. Could anyone out there give me any tips on something I may be overlooking as a newbie coder?
Here is my index.js page:
module.exports = function Route (app, server) {
// this gets the socket.io module (below)
var io = require("socket.io").listen(server)
var counter = 0; //saves the count
io.sockets.on("connection", function(socket){
socket.on("push_button", function(data){
counter +=1;
io.emit("push_counter", {response: counter});
/* io.emit is a full broadcast, thus sends data to all connectd clients
will send counter number to index.ejs after increasing by 1 */
})
socket.on("reset_counter", function(data){
counter = 0;
io.emit("reset_response", {response: counter});
/* Will set counter to 0 and send to index.ejs */
})
})
// root route to render the index.ejs view (below)
app.get("/", function(request, response){
response.render("index");
})
};
Here is my index.ejs file that I have stored in a views folder. This page contains the reset function:
<!DOCTYPE HTML>
<html lang ="en US">
<head>
<meta charset="UTF-8">
<title>Epic Button Game</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type ="text/javascript" src="/socket.io/socket.io.js"></script>
<script type ="text/javascript">
$(document).ready(function (){
// alert("jquery loaded");
var socket = io.connect();
//lets emit an event when somebody pushes the button
$("#push").click(function(){
socket.emit("push_button", {action: "Somebody pushed the button"});
});
// this event will emit to the server to reset the counter into 0
$('#reset').click(function(){
socket.emit("reset_counter", {action: 'Resetting the counter'});
});
// listen to the push_counter event from server
socket.on("push_counter", function (data){
console.log(data); // <----- used to test if counter is working
$("#message").html("The button has been pushed " + JSON.stringify(data.response) + " time(s)");
// Will display message on local host page (above code)
});
// Will listen to the reset_response event from server
socket.on('reset_response', function (data){
console.log(data);
$('#message').html('');
});
})
</script>
</head>
<body>
<center>
<h2 id="message">Reset needs to be fixed!</h2>
<h4>Push the button to update the count!</h4>
<button id="push">Push this awesome button</button>
<button id="reset">Reset Count</button>
</center>
</body>
</html>
Here is my server.js page:
// require express, path, body-parser
var express = require("express");
var path = require("path");
var bodyParser = require('body-parser');
// create the express app
var app = express();
app.use(bodyParser.urlencoded());
// static content
app.use(express.static(path.join(__dirname, "./static")));
// setting up ejs and our views folder
app.set('views', path.join(__dirname, './views'));
app.set('view engine', 'ejs');
// tell the express app to listen on port 3000
var server = app.listen(3000, function() {
console.log("listening on port 3000");
})
//we're going to have /routes/index.js handle all of our routing
var route = require('./routes/index.js')(app, server);
Finally my package.json page which contains a list of dependencies I am using:
{
"name": "epic_button_game",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"ejs": "^2.5.5",
"express": "^4.14.1",
"socket.io": "^1.7.2"
}
}
Thanks for in advance for any suggestions.

Categories