all:
I have an API call using express and I'm wanting the data to load into an existing paragraph tag on the html page with the form, but currently it loads into a new html page using res.send(). Have checked the express documentation and cannot find anything. Any ideas how I can do this? Here is the code:
const express = require('express');
const app = new express();
const port = 3000;
const request = require('request');
app.use(express.urlencoded({extended: true}));
app.get("/", (req, res) => {
res.sendFile(`${__dirname}/index.html`);
})
app.post("/", (req, res)=>{
let crypto = req.body.crypto;
let fiat = req.body.fiat;
request(`https://apiv2.bitcoinaverage.com/indices/global/ticker/${crypto}${fiat}`, function (error, response, body) {
let data = JSON.parse(body);
let price = data.last;
res.write(`<h1>${price}</h1>`);
});
})
app.listen(port, ()=>{
console.log('Listening on port 3000');
})
Thank you all so much,
Kevin
Related
whats wrong with my code? its showing no results....although it kinda works when i use google.com as url but in other cases it shows no results*I haven't shared my api key here(appid=)
const express = require('express');
const app = express();
const http = require('http');
app.get("/", function(req, res) {
const url= 'https://api.openweathermap.org/data/2.5/weather?q=london&appid='
http.get(url, function(response){
console.log(response);
// response.on("data", function(data){
// const weatherData = JSON.parse(data);
// const temp = weatherData.main.temp;
// // const weatherDescription = weatherData.weather[0].description;
// res.send(temp)
// })
// res.send('server is sending');
})
})
app.listen(3000, function(req, res){
console.log('Server is alive')
})
I want to send serial port data to a browser UI with express. So far my code looks like this:
var SerialPort = require("serialport");
var serialport = new SerialPort("/dev/cu.usbmodem1421");
var express = require('express');
var app = express();
var datenFromA;
serialport.on('open', function(){
console.log('Serial Port Opend');
serialport.on('data', function(data){
datenFromA = data[0];
console.log(datenFromA);
});
});
app.get('/', function (req, res) {
res.send('Hello World')
})
app.listen(3000);
Instead of the 'Hello World' I want to send the value of variable datenFromA to the browser. Any ideas how to pass the value to the app.get function?
Thanks in advance.
Essentially you need to wait until you receive an event. Quick dirty example given below:
const SerialPort = require("serialport");
const serialport = new SerialPort("/dev/cu.usbmodem1421");
const express = require('express');
const app = express();
// Only need to do this once.
serialport.on('open', () => console.log('Serial Port Opend'));
app.get('/', async (req, res) => {
const promise = new Promise((resolve, reject) => {
serialport.on('data', (data, err) => {
if (err) {
reject(err);
return;
}
resolve(data[0]);
});
})
const data = await promise;
res.json(data);
})
app.listen(3000);
GET /user/me - sends back 404 (resource not found)
If I change the second '/' to a '_' (i.e GET users_me), then it works.
I have two questions:
1) How to fix it so I can use 'GET /user/me'?
2) It works with an underscore so is there any advantage to using the slash vs. the underscore?
///////////Code
require('./config/config');
const _ = require('lodash');
const express = require('express');
const bodyParser = require('body-parser');
const {ObjectID} = require('mongodb');
//const multer = require('multer');
//const router = express.Router();
var renameKeys = require('rename-keys');
var {mongoose} = require('./db/mongoose');
//var {Todo} = require('./models/todo');
var {User} = require('./models/user');
var {authenticate} = require('./middleware/authenticate');
var app = express();
const port = process.env.PORT;
app.use(bodyParser.json());
// GET users/me
app.get('/users_me', authenticate, (req, res) => {
res.send(req.user);
});
// POST /users -- signing up a new user [how will this handle logging in instead of signing up?]
app.post('/users', (req, res) => {
var body = _.pick(req.body, ['email', 'password']);
var user = new User(body);
user.save().then(() => {
return user.generateAuthToken();
}).then((token) => {
res.header('x-auth', token).send(user);
}).catch((e) => {
res.status(400).send(e);
})
});
app.listen(port, () => {
console.log(`Started up at port ${port}`);
});
module.exports = {app};
First question:
Just change
app.get('/users_me', authenticate, (req, res) => {
res.send(req.user);
});
to
app.get('/users/:me', authenticate, (req, res) => {
res.send(req.user);
});
Then make a Get request:
somehost:someport/users/myusername
Second question:
Routing works just like a file-system:
/path/subpath/
So you can't use an underscore to substitute a slash '/'
INFO: You could pass the id or name (depends on your logic) of the user in the URL of your GET-request:
GET request (in this case to localhost with port 3000):
localhost:3000/users/getuserbyid/20
route:
router.get('/getuserbyid/:id', .....
Hope that helps ;)
Can someone help me why default route is not working in my Mean App, But the next routing works
Here when I open http://localhost:3000 I am not able to see any output, But I have defined route in route.js which is working
var express = require('express');
var cors = require('cors');
var bodyparser = require('body-parser');
var mongoose = require('mongoose');
var path = require('path');
const port = 3000;
app.get('/', function (req, res) {
res.send('Test');
console.log('Opened the root path');
});
When I open the page with http://localhost:3000/main I am able to see the Output and also log written in the console
const express = require('express');
const router = express.Router();
router.get('/main', function (req, res, next) {
res.send('This is the Admin Landing Page');
});
router.get('/install', function (req, res, next) {
res.send('This is the Install Landing Page');
console.log('Opened the Install path');
});
module.exports = router;
It looks like you the code you pasted is the full version, and it's not runnable because:
You did not declare app variable.
You did not start the http server.
It's really hard to tell the root cause what's wrong of your code. Following codes works for me:
const express = require('express');
const port = 3000;
let app = express();
app.get('/', function (req, res) {
res.send('Test');
console.log('Opened the root path');
});
let server = require('http').createServer(app);
server.listen(port, function() {
console.log('Server started');
});
I am building a quick Express JS application. I have sent data to Redis from another application.
I did an LPUSH. I was able to do this:
client.lrange('stash', 0, 10, function(err, reply) {
console.log(reply);
});
My goal is to, instead of doing a console.log("..."), I want to send it to a in my index.html.
Any ideas on how to do this?
EDIT: Here is my app.js file:
var express = require('express');
var redis = require('redis');
var app = express();
app.use(express.static('public')); //used to get image
app.engine('html', require('ejs').renderFile); //ejs, not handlebars
function index(req,res, next) {
testController.index(req, res, next);
}
app.get('/', function(req, res){
res.render('index.html');
});
app.get('*', function(req, res){
res.render('404.html');
});
//redis stuff
var client = redis.createClient();
client.on('connect', function() {
console.log('connected');
});
client.lrange('stash', 0, 10, function(err, reply) {
console.log(reply); //instead of this, let's place that into a div
});
//end redis
app.listen(3000, function(){
console.log('My example app is now running! (3000)')
});
from my understanding you could use ejs to plug in data directly into your html. The problem of course is that I don't know how client.lrange works but I know that express reads middleware top to bottom. If lrange is pulling data you need from the db you can save the data to a global var data and on a call to the endpoint of the html you want updated; render it with ejs.
create a place holder for the data
var data;
pull the data from server and save globally
client.lrange('stash', 0, 10, function(err, reply) {
data = reply;
});
render html page with ejs using ejs tags
app.get('/', function(req, res) {
res.render('index.html', {reddisData: data});
});
plug it into your html
<a>
<%= reddisData %>
</a>
all together
var express = require('express');
var path = require('path');
app = express()
app.engine('html', require('ejs').renderFile);
app.set('html', 'ejs');
var data;
client.lrange('stash', 0, 10, function(err, reply) {
data = reply;
});
app.get('/', function(req, res) {
res.render('index.html', {reddisData: data});
});
Hope this helps, if it doesn't work for you the idea is what counts. Look into using ejs to resolve your problem.