I am currently trying to make a webapp that uses the darksky api to pull weather data. I have the basic functionality done, but when I try to run it on port 3000, I get "Cannot GET/". I am quite new to using node and backend servers as a whole so I don't know how to debug this. I will paste my code below.
const express = require("express");
const unirest = require("unirest");
const credentials = require('./apiCredentials.json');
const app = express();
app.use(express.static('/public')); // location of my index.html
app.get('/weather', (req, res) => {
const {lat,lon} = req.query;
let request = unirest("GET",`https://${credentials.host}/${lat},${lon}`);
request.query({
lang:"en",
units:"auto"
});
request.headers({
"dark-sky.p.rapidapi.com": credentials.host,
"466375f66bmsh72031b571ea7c30p1f704fjsnc527236c3565": credentials.apiKey
});
request.end(response => {
if(response.error) res.status(500).end();
const{
summary,
precipProbability,
temperature,
windSpeed,
windBearing
} = response.body.currently;
res.status(200).send(
JSON.stringify({
summary: summary,
chanceOfRain: precipProbability,
temp: temperature,
wind:{
speed: windSpeed,
bearing: windBearing
}
})
);
});
});
app.listen(3000,()=>{
console.info('Listening on port :3000');
});
Related
So I have a web app I've built with react and javascript that consists of a server side and a client side.
This is what I set up on the server app.js:
require("./DB/connectToDb");
// require("./primeryData/primeryCards")();
const express = require("express");
const app = express();
const rateLimit = require("express-rate-limit");
const usersRouter = require("./Routes/Users/userRouter");
const cardsRouter = require("./Routes/Cards/cardsRouter");
const ordersRouter = require("./Routes/Orders/OrderRouter");
const chalk = require("chalk");
const morgan = require("morgan");
const cors = require("cors");
app.use(morgan(chalk.cyan(":method :url :status :response-time ms")));
app.use(cors());
app.use(express.json());
app.use("/api/users", usersRouter);
app.use("/api/cards", cardsRouter);
app.use("/api/orders", ordersRouter);
const PORT = 8181;
app.listen(PORT, () =>
console.log(chalk.blueBright.bold(`server run on: http://:localhost:${PORT}`))
);
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 10, // Limit each IP to 100 requests per `window` (here, per 15 minutes)
message: "Limited I Guess..."
})
app.get("/",limiter,(req,res)=>res.send(req.ip));
app.use('/api', limiter);
When I go to the Browser with http://localhost:8181/ I get my IP which is ::1
After refreshing >10 times I get "Limited I Guess..." as it should.
However when I try and use my client side to make requests nothing happens, I can make a million server calls!!!
Am I missing something? Does express-rate-limit not work when client side is making the server calls?
An example of my server api:
/********** Like/Dislike Card **********/
router.patch("/card-like/:id", auth, async (req, res) => {
try {
// console.log(req.params.id);
const user = req.user;
let card = await Card.findOne({ _id: req.params.id });
const cardLikes = card.likes.find((id) => id === user._id);
if (!cardLikes) {
card.likes.push(user._id);
card = await card.save();
return res.send(card);
}
const cardFiltered = card.likes.filter((id) => id !== user._id);
card.likes = cardFiltered;
card = await card.save();
return res.send(card);
} catch (error) {
console.log(chalk.redBright("Could not edit like:", error.message));
return res.status(500).send(error.message);
}
});
I was using the library in app.js, tried using it in api.js and worked I guess, app.js was unaware of what was going on in api.js even though it was required.
I have a frontend JS script that takes text input from an HTML text box and sends it to an expressjs server. The body of the POST request, though, is always undefined, or depending on how I tweak things, returning as "{ }" if I view it via console.log( ). As I'm new to this, I can't seem to see what's going wrong.
Front end js:
async function submitCity(){
let x = document.getElementById("wg_input").value;
console.log("Successfully captured city name:", x);
let toWeather = JSON.stringify(x);
console.log("Input data successfully converted to JSON string:", toWeather);
const options = {
method: 'POST',
mode: 'cors',
headers: {'Content-Type': 'text/plain'},
body: toWeather
}
fetch('http://localhost:3000', options)
.then(res => console.log(res))
.catch(error => console.log(error))
}
Backend:
// Dependencies
const express = require('express');
const bp = require("body-parser");
const request = require("request");
const jimp = require('jimp');
const cors = require('cors');
const wgServer = express();
const port = 3000;
// Dotenv package
require("dotenv").config();
// OpenWeatherMap API_KEY
const apiKey = `${process.env.API_KEY}`;
// Basic server initialization
wgServer.use(cors())
wgServer.use(bp.json())
wgServer.use(bp.urlencoded({ extended: true }))
wgServer.listen(port, function() {
console.log(`Example app listening on port ${port}!`)
});
wgServer.post('/', async function (req, res) {
res.set('Content-Type', 'text/plain');
console.log(req.body)
res.send('Hello World');
//const data = await req.body;
// let jsonData = JSON.stringify(req.body);
// res.status(201);
//res.json();
});
The returned data is supposed to be a string of about 15 characters, give or take a few (a city and state). I thank you in advance.
I'm trying to connect from Nodejs to DialogFlow. I have completed all the steps to configure the user agent, the intent, etc. If I lunch with NODEMON the app, all its ok, but when I send a GET or POST request I get this error:
"UnhandledPromiseRejectionWarning: TypeError: sessionClient.projectAgentSessionPath" and more. But I think the most relevant mistake is this.
The code I used it's the same as the APi docs. I don't know why I get this error.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const dialogflow = require('#google-cloud/dialogflow');
const uuid = require('uuid');
//const sendReq = require('./reqDialogFlow');
async function runSample(projectId = 'helpcenter-qwoj') {
// A unique identifier for the given session
const sessionId = uuid.v4();
// Create a new session
const sessionClient = new dialogflow.SessionsClient();
const sessionPath = sessionClient.projectAgentSessionPath(projectId, sessionId);
console.log(sessionPath);
// The text query request.
const request = {
session: sessionPath,
queryInput: {
text: {
// The query to send to the dialogflow agent
text: 'hello',
// The language used by the client (en-US)
languageCode: 'it',
},
},
};
// Send request and log result
const responses = await sessionClient.detectIntent(request);
console.log('Detected intent');
const result = responses[0].queryResult;
console.log(` Query: ${result.queryText}`);
console.log(` Response: ${result.fulfillmentText}`);
if (result.intent) {
console.log(` Intent: ${result.intent.displayName}`);
} else {
console.log(` No intent matched.`);
}
};
app.get('/', (req, res) => {
res.send({ "hello": "Daniele Asteggiante" })
});
app.post('/api/textAPIE', (req, res) => {
res.send({ "text": "CIAO" });
runSample();
});
app.use(bodyParser.json());
const PORT = process.env.PORT || 5000;
app.listen(PORT);
i had the same error.
i had installed
npm i dialogflow
instead of
npm install #google-cloud/dialogflow
I tried to change the Express Version version with an earlier version 4.17.0 instead 4.17.1.
Now it goes.
change "sessionClient.projectAgentSessionPath" -> "sessionClient.sessionPath"
Found this solution on github:https://github.com/googleapis/nodejs-dialogflow/issues/127
I seem to have gotten backend index.js file working with an apple-pay payment request on the back-end. However the results do not show up in my Stripe dashboard. Spinning my wheels and cannot figure out why. Any help would be much appreciated.
Below is the code I am using on the back-end. When I press the pay button in Apple-Pay in the App, my terminal window shows "Payment requested" and "Success" messages.
I would then expect the USD amount to process in my stripe dashboard but I am gettin $0.00 and no activity. Any help would be wonderful!
// Add packages we need
const express = require('express')
const bodyParser = require('body-parser')
var stripe = require('stripe')('YOUR-SECRET-KEY')
// Create an express app
const app = express()
// Use body parser so we can parse the body of requests
app.use(bodyParser.json())
// Just a sanity check endpoint we can hit in the browser
app.get('/', function (req, res) {
res.send('This is the backend server for Metatoll Application!')
})
app.post('/pay', function (req, res) {
console.log('Payment requested')
var token = req.body.stripeToken
var amount = req.body.amount
var description = req.body.description
stripe.charges.create({
amount: amount,
currency: "usd",
description: description,
source: token,
}, function(err, charge) {
if (err !== null) {
console.log('error capturing')
console.log(err)
res.status(400).send('error')
} else {
console.log('success')
res.status(200).send('success')
}
});
})
app.listen(3000, () => {
console.log('Metatoll listening on port 3000')
})
I have a RESTful API that I am using postman to make a call to my route /websites. Whenever I make the call, postman says "Cannot POST /websites". I am trying to implement a job queue and I'm using Express, Kue(Redis) and MongoDB.
Here is my routes file:
'use strict';
module.exports = function(app) {
// Create a new website
const websites = require('./controllers/website.controller.js');
app.post('/websites', function(req, res) {
const content = req.body;
websites.create(content, (err) => {
if (err) {
return res.json({
error: err,
success: false,
message: 'Could not create content',
});
} else {
return res.json({
error: null,
success: true,
message: 'Created a website!', content
});
}
})
});
}
Here is the server file:
const express = require('express');
const bodyParser = require('body-parser');
const kue = require('kue');
const websites = require('./app/routes/website.routes.js')
kue.app.listen(3000);
var app = express();
const redis = require('redis');
const client = redis.createClient();
client.on('connect', () =>{
console.log('Redis connection established');
})
app.use('/websites', websites);
I've never used Express and I have no idea what is going on here. Any amount of help would be great!!
Thank you!
The problem is how you are using the app.use and the app.post. You have.
app.use('/websites', websites);
And inside websites you have:
app.post('/websites', function....
So to reach that code you need to make a post to localhost:3000/websites/websites. What you need to do is simply remove the /websites from your routes.
//to reach here post to localhost:3000/websites
app.post('/' , function(req, res) {
});