Cant find the problem an express server problem - javascript

i have an express server which has the code:
// Setup empty JS object to act as endpoint for all routes
projectData = {};
// Require Express to run server and routes
const express = require('express');
// Start up an instance of app
const app = express();
/* Dependencies */
const bodyParser = require('body-parser');
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
const cors = require('cors');
app.use(cors());
// Initialize the main project folder
app.use(express.static('website'));
const port = 8000;
// Setup Server
const server = app.listen(port, listening);
function listening(){
// console.log(server);
console.log(`running on localhost: ${port}`);
};
app.get('/all', sendData);
function sendData (req, res) {
res.send(projectData);
};
app.post('/all', receiveData);
function receiveData (req, res) {
projectData.temp = req.body.temp;
projectData.date = req.body.date;
projectData.ures = req.body.ures;
res.send(projectData);
console.log(projectData);
}
so simply i am making a weather journal app which receives data from an API and shows it to the user and this is the index look like:
so basically the user is going to write the zip code and feelings and when clicking on the button generate the entry should contain the information like this
but when the user click the button generate this shows and the user have to click it again in order to show the information like the top picture:
and this is the JavaScript code for the client-side:
/* Global Variables */
let baseURLz = 'http://api.openweathermap.org/data/2.5/weather?zip=';
let baseURLa = '&appid=';
const apiKey = '8e017daef09d7f784c8595696bdcb587';
// Create a new date instance dynamically with JS
let d = new Date();
let newDate = d.getMonth()+'.'+ d.getDate()+'.'+ d.getFullYear();
document.getElementById('generate').addEventListener('click', performAction);
function performAction(e){
const zipcode = document.getElementById('zip').value;
const ures = document.getElementById('feelings').value;
getWeather(baseURLz, zipcode, baseURLa, apiKey)
.then(function(data){
console.log(data);
postData('/all', {temp: data.main.temp, date: newDate, ures: ures});
})
.then(
updateUI()
)
}
const getWeather = async (baseURLz, zipcode, baseURLa, apikey)=>{
const res = await fetch(baseURLz+zipcode+baseURLa+apikey+'&units = imperial')
try {
const data = await res.json();
console.log(data)
return data;
} catch(error) {
console.log("error", error);
// appropriately handle the error
}
}
const postData = async ( url = '', data = {})=>{
const res = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data), // body data type must match "Content-Type" header
});
try {
const newData = await res.json();
return newData;
}catch(error) {
console.log("error", error);
}
};
const updateUI = async () => {
const req = await fetch('/all');
try{
const allData = await req.json();
document.getElementById('date').innerHTML = 'Date: '+allData.date;
document.getElementById('temp').innerHTML = 'Temperature: '+allData.temp+'°F';
document.getElementById('content').innerHTML = 'Feelings: '+allData.ures;
}catch(error){
console.log("error", error);
}
}
and this is the html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Weather Journal</title>
<link href="https://fonts.googleapis.com/css?family=Oswald:400,600,700|Ranga:400,700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id = "app">
<div class ="holder headline">
Weather Journal App
</div>
<div class ="holder zip">
<label for="zip">Enter Zipcode here</label>
<input type="text" id="zip" placeholder="enter zip code here">
</div>
<div class ="holder feel">
<label for="feelings">How are you feeling today?</label>
<textarea class= "myInput" id="feelings" placeholder="Enter your feelings here" rows="9" cols="50"></textarea>
<button id="generate" type = "submit"> Generate </button>
</div>
<div class ="holder entry">
<div class = "title">Most Recent Entry</div>
<div id = "entryHolder">
<div id = "date"></div>
<div id = "temp"></div>
<div id = "content"></div>
</div>
</div>
</div>
<script src="app.js" type="text/javascript"></script>
</body>
</html>
please i want to figure out where is the problem causing this to happen.

Related

React Contact Form 404 not Found

I'm trying to create a contact form in react with node mailer but Im having the following issue:
Error shown in console on the browser
It says that 404 NOT FOUND but I dont know where is the mistake i have tried changing the listening part of the server file but no luck:
import React from 'react';
import { useState } from 'react';
import './contactForm.css';
import { Footer } from '../../containers';
const FORM_ENDPOINT = "";
const ContactForm = () => {
const [status, setStatus] = useState("Submit");
const handleSubmit = async (e) => {
e.preventDefault();
setStatus("Sending...");
const { name, email, message } = e.target.elements;
let details = {
name: name.value,
email: email.value,
message: message.value,
};
let response = await fetch("http://localhost:3000/contactForm", {
method: 'POST',
headers: {
"Content-type": "application/json;charset=utf-8",
},
body: JSON.stringify(details),
});
setStatus("Submit");
// let result = await response.json();
// alert(result.status);
};
return (
<div className='RO__ContactForm' id='contactForm'>
<div className='RO__ContactForm-title'>
<h3>Contact</h3>
<h1>I'm here to help you level up</h1>
</div>
<div className='RO__ContactForm-content'>
<div className='RO__ContactForm-content_description'>
<p>I'm just on click away to help you take your company
to the next level. Fill in the form to share more
details about the project or your favorite movie.
Either way, I'd love to talk.</p>
<p></p>
</div>
<form
className='RO__ContactForm-content_form'
action = {FORM_ENDPOINT}
onSubmit = {handleSubmit}
method = 'POST'
target='_blank'
>
<div className='RO__ContactForm-content_form_name'>
<div className='RO__ContactForm-content_form_nameTitle'>
<h5>What's your name?</h5>
</div>
<input
className='RO_ContactForm-content_form_nameInput'
type= 'text'
id='name'
name='name' required
/>
</div>
<div className='RO__ContactForm-content_form_email'>
<div className='RO__ContactForm-content_form_emailTitle'>
<h5>Your email</h5>
</div>
<input
className='RO__ContactForm-content_form_emailInput'
type='email'
id='email['
name='email' required
/>
</div>
<div className='RO__ContactForm-content_form_info'>
<div className='RO__ContactForm-content_form_infoTitle'>
<h5>What can I help you with?</h5>
</div>
<textarea
className='RO__ContactForm-content_form_infoContent'
id='message'
name='message' required
/>
</div>
<div className='RO__ContactForm-content_form_button'>
<button type='submit'>{status}</button>
</div>
</form>
</div>
<div className='RO__ContactForm-footer'>
<Footer />
</div>
</div>
)
}
export default ContactForm
and here is the server file that I use to initialize the server to send the email. That file is made for the contact form front end, and the following file (server.js) its the following;:
const express = require("express");
const router = express.Router();
const cors = require("cors");
const nodemailer = require("nodemailer");
const app = express();
app.use(cors());
app.use(express.json());
app.use('/', router);
app.listen(3000, () => console.log("Server Running"));
const contactEmail = nodemailer.createTransport({
service: "Hotmail",
auth: {
user: '*************#hotmail.com',
pass: '************',
},
});
contactEmail.verify((error) => {
if(error){
console.log(error);
}
else{
console.log("Ready to Send");
}
});
router.post("/contactForm", (req, res) => {
const name = rew.body.name;
const email = req.body.email;
const message = req.body.message;
const mail = {
from: name,
to: 'invariant.rafael.3096#getDefaultNormalizer.com',
subject: 'Contact Form Submission',
hmtl: '<p>Name: ${name} </p> <p>Email: ${email}</p> <p>Message: ${message}</p>',
};
contactEmail.sendMail(mail, (error) => {
if(error){
res.json({ status: 'Error'});
}
else{
res.json({ status: 'Message Sent' });
}
});
});
React typically hosts on port 3000. Change the express server to run on a different port: app.listen(CHANGEME, () => console.log("Server Running"));
If that doesn't work try making some fetch requests somewhere else e.g. https://api.publicapis.org/entries which is a free testing API. Then you will know whether the problem is with your server or not.

How can I send a POST request to display a message to an html file using axios?

I'm using the weatherstack API and want to send the current temperature of a given city to a simple form in html using the POST method in express (or axios, if possible).
I tried to use the GET method in axios to consume the API and the POST method in express to send the result once the user enters the city they want in the search bar. The code is the following:
app.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const axios = require('axios');
const access_key = '...'
app.use(bodyParser.urlencoded({extended: false}));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
// Successful GET in the console
// axios.get(`http://api.weatherstack.com/current?access_key=${access_key}&query=Dallas`)
// .then(response => {
// const apiResponse = response.data;
// console.log(`Current temperature in ${apiResponse.location.name} is ${apiResponse.current.temperature}℃`);
// }).catch(error => {
// console.log(error);
// });
// ----The problem-------
app.post('/', async function (req, res) {
const{response} = await axios(`http://api.weatherstack.com/current?access_key=${access_key}&query=${req.body.cityName}`)
res.send(`<p>Current temperature in ${req.body.cityName} is ${response.current.temperature} ℃</p>
<a href = '/'>Back</a>`)
});
//------------------------
app.listen({port: 4000}, () => {
console.log("Server running on localhost:4000");
});
The website
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weatherstack</title>
</head>
<body>
<form action="/" method="post">
<p>Inform the city</p>
<input name="cityName">
<button type="submit">Send</button>
</form>
</body>
</html>
But when I run the server I get this error:
How can I solve that?
Axios return the AxiosResponse object.
export interface AxiosResponse<T = any, D = any> {
data: T;
status: number;
statusText: string;
headers: RawAxiosResponseHeaders | AxiosResponseHeaders;
config: AxiosRequestConfig<D>;
request?: any;
}
the content of your response is within the data object.
const { data } = await axios(
`http://api.weatherstack.com/current?access_key=${access_key}&query=${req.body.cityName}`
);
res.send(
`<p>Current temperature in ${req.body.cityName} is ${data.current.temperature} ℃</p><a href = '/'>Back</a>`
)
Or
const response = await axios(
`http://api.weatherstack.com/current?access_key=${access_key}&query=${req.body.cityName}`
);
res.send(
`<p>Current temperature in ${req.body.cityName} is ${response.data.current.temperature} ℃</p><a href = '/'>Back</a>`
)
I tested this code, and it works fine.

I'm not able to change h3 from app.js after getting data from api server

I'm trying to change element h3 of index.html when I receive data from API server
code of index.html
<form action="/" class="" method="POST">
<h1 class=""><span class="clr-dark-purple">VPN</span> & <span class="clr-dark-purple">Proxy</span> Detection.</h1>
<h2>Test to see if an IP address is either a VPN, Proxy, or a TOR node</h2>
<input type="text" name="ip" class="css-input" placeholder="Enter IP Address" required autofocus> <br>
<div class="container-one">
<button type="submit">
Test
<div class="fill-one"></div>
</button>
</div>
<h3></h3>
</form>
code in app.js
app.get("/",function(req,res)
{
res.sendFile(__dirname + "/index.html");
})
app.post("/",function(req,res){
const apikey = "my-api-key";
const ip = req.body.ip;
const url = "https://vpnapi.io/api/" + ip + "?key=" + apikey +"";
console.log(ip, url);
https.get(url,function(response)
{
console.log(response.statusCode);
const chunks = [];
response.on('data', function (chunk) {
chunks.push(chunk)
})
response.on('end', function () {
const data = Buffer.concat(chunks)
var deta = JSON.parse(data)
var vpn = deta.security.vpn;
var proxy = deta.security.proxy;
var city = deta.location.city;
res.write(`<h3><span style="margin-right:1.3em"><span style="color:#301b3f;">VPN:</span> ${vpn}</span><span style="margin-right:1.3em;"><span style="color:#301b3f;">Proxy:</span> ${proxy}</span> <span><span style="color:#301b3f;">City:</span> ${city}</span></h3>
`);
console.log(vpn,proxy,city);
})
})
});
I'm not able to change the content of h3, Help!
Everything else working fine. Thanks.
Keep index.html as it is.
I have commented down some code as I didn't have the API key required in them.
Just replace res.write() with res.send().
app.js
const express = require('express')
const app = express()
const path = require('path')
const https = require('https');
app.use('/public', express.static(path.join(__dirname, 'static')));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
})
app.post("/", function (req, res) {
//const apikey = "my-api-key";
//const ip = req.body.ip;
// const url = "https://vpnapi.io/api/" + ip + "?key=" + apikey + "";
const url = "https://vpnapi.io/api/";
//console.log(ip, url);
https.get(url, function (response) {
console.log(response.statusCode);
const chunks = [];
response.on('data', function (chunk) {
chunks.push(chunk)
})
response.on('end', function () {
const data = Buffer.concat(chunks)
var deta = JSON.parse(data)
var vpn = deta.security.vpn;
var proxy = deta.security.proxy;
var city = deta.location.city;
console.log(vpn, proxy, city);
res.send(`<h3><span style="margin-right:1.3em"><span style="color:#301b3f;">VPN:</span> ${vpn}</span><span style="margin-right:1.3em;"><span style="color:#301b3f;">Proxy:</span> ${proxy}</span> <span><span style="color:#301b3f;">City:</span> ${city}</span></h3>
`);
})
})
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Application running on PORT ${port}`);
})

Error in the url passed when I connect to a weather api

This is my first app doing it with node.js and express. This is a basic app where I connect to an external API to show temperature and take a user input "city and feeling" and show it to the UI. I can't get the URL right. I don't know why.
I ran the app and entered data in the city and feeling text area, I debugged the app.js file and found that when it tries to fetch the URL I'm passing its data it gives the error "400 bad requests". What am I doing wrong?
the server.js
// Setup empty JS object to act as endpoint for all routes
projectData = {};
// Require Express to run server and routes
const express = require('express');
// Start up an instance of app
const app = express();
/* Middleware*/
//body-parser as the middle ware to the express to handle HTTP POST
const bodyParser = require('body-parser');
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
const cors = require('cors');
app.use(cors());
// Initialize the main project folder , this line allows talking between server and client side
app.use(express.static('website'));
// Setup Server
const port = 8000;
const server = app.listen(port , ()=>{console.log(`the server running on localhost: ${port}`);});
//GET function
app.get('/fakeData' , getFakeData); //string represents a url path >> / means home
function getFakeData (req,res) {
// body...
console.log(projectData);
res.send(projectData);
}
var project = [];
app.get('/all', sendData);
function sendData (request, response) {
response.send(project);
console.log(project);
};
//POST function
app.post('/addAnimal' ,addAnimal);
function addAnimal (req,res) {
// body...
newEntry = {
date: req.body.date,
temp: req.body.main.temp,
feeling: req.body.feeling
}
project.push(newEntry)
res.send(project)
console.log(project)
}
website/app.js
/* Global Variables */
//let baseURL = 'http://api.openweathermap.org/data/2.5/weather?q=Egypt&APPID=';
let baseURL = `http://api.openweathermap.org/data/2.5/weather?city=`;
let apiKey = '&APPID=bb95e29dbedc4d929be90b0dd99954e0';
// Create a new date instance dynamically with JS
let d = new Date();
let newDate = d.getMonth()+'.'+ d.getDate()+'.'+ d.getFullYear();
//GET request to handle user input
document.getElementById('generate').addEventListener('click', performAction);
function performAction(e){
//Take user input
//const zipcode = document.getElementById('zip').value; //no
const feeling = document.getElementById('feelings').value;
const city = document.getElementById('zip').value;
//the fake api call
//getAnimal('/fakeAnimalData')
getTemp(baseURL ,city , apiKey )
.then (function(data) {
// body...
console.log(data)
postData('/addAnimal' ,{temp:data.main.temp ,date:newDate, feeling:feeling} )
//updateUI()
})
.then(
updateUI()
)
};
const getTemp = async(baseURL ,city , apiKey)=>{
const res = await fetch(baseURL+city+apiKey)
try{
const data = await res.json();
console.log(data)
return data;
}
catch(error){
console.log("error" , error);
}
}
//make a POST request to our route , POST to store locally user-input data
const postData = async(url='' , data={})=>{
//console.log(data);
const response = await fetch(url , {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
// Body data type must match "Content-Type" header
body: JSON.stringify(data),
});
try {
const newData = await response.json();
console.log(newData);
return newData
}catch(error){
console.log("error", error);
}
}
const updateUI = async () => {
const request = await fetch('/all');
try{
const allData = await request.json()
console.log(allData);
document.getElementById('date').innerHTML = allData[0].date;
document.getElementById('temp').innerHTML = allData[0].temp;
document.getElementById('content').innerHTML = allData[0].feeling;
}catch(error){
console.log("error", error);
}
}
website/index.js
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Weather Journal</title>
<link href="https://fonts.googleapis.com/css?family=Oswald:400,600,700|Ranga:400,700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id = "app">
<div class ="holder headline">
Weather Journal App
</div>
<div class ="holder zip">
<label for="zip">Enter Zipcode here</label>
<input type="text" id="zip" placeholder="enter zip code here">
</div>
<div class ="holder feel">
<label for="feelings">How are you feeling today?</label>
<textarea class= "myInput" id="feelings" placeholder="Enter your feelings here" rows="9" cols="50"></textarea>
<button id="generate" type = "submit"> Generate </button>
</div>
<div class ="holder entry">
<div class = "title">Most Recent Entry</div>
<div id = "entryHolder">
<div id = "date"></div>
<div id = "temp"></div>
<div id = "content"></div>
</div>
</div>
</div>
<script src="app.js" type="text/javascript"></script>
</body>
</html>
There seems no issue in your url making. I have opened http://api.openweathermap.org/data/2.5/weather?city=cairo&APPID=bb95e29dbedc4d929be90b0dd99954e0 in browser and its returning HTTP 400 Bad Request as status code and due to 400 status code the browser is telling that the request failed.
Here is response. {"cod":"400","message":"Nothing to geocode"}
The original issue, it seems, is your city parameter that your are sending.
However if you change city parameter in your url to q, it seems to work.
http://api.openweathermap.org/data/2.5/weather?q=cairo&appid=bb95e29dbedc4d929be90b0dd99954e0
Here is response. {"coord":{"lon":31.25,"lat":30.06},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"base":"stations","main":{"temp":295,"feels_like":293.65,"temp_min":294.82,"temp_max":295.15,"pressure":1015,"humidity":64},"visibility":10000,"wind":{"speed":4.1,"deg":290},"clouds":{"all":75},"dt":1584185538,"sys":{"type":1,"id":2514,"country":"EG","sunrise":1584158752,"sunset":1584201751},"timezone":7200,"id":360630,"name":"Cairo","cod":200}

Passing data from Client to Server

In my code I want to pass an id from client to server.
I am trying to use fetch setting the Content-Type to Application/json but it looks like we have some problems (I analized the request and it doesn't create the body).
Is there a simply way to pass data from client to server?
{#each accounts}}
<form action="/users/chat" method="POST">
<div class="form-group">
<p>{{#index}}</p>
<label for="name" value={{username}}>{{username}}</label>
</div>
<div class="form-group">
<label for="name">{{email}}</label>
</div>
<button class="myButton" id="{{#index}}">chat</button>
</form>
{{else}}
<p>No account</p>
{{/each}}
<script>
const buttons = document.getElementsByClassName('myButton');
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function(e) {
let ident=this.id;
console.log(ident);
console.log('button was clicked');
fetch("/myurl",{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify({id : ident})
})
}
</script>
Here is the code of the server:
var express = require('express');
var router = express.Router();
var app = express();
var bcrypt = require('bcryptjs');
const db = require('../config/database');
const Account = require('../models/Account');
const chat = require('../models/chat');
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
var passport = require('passport');
LocalStrategy = require('passport-local').Strategy;
const {ensureAuthenticated}=require('../config/auth');
app.use(express.urlencoded());
app.use(express.json());
//Socket
const PORTS = process.env.PORT || 7001;
var client = require('socket.io').listen((PORTS, console.log`SOCKET started on port ${PORTS}`)).sockets;
var password;
var username;
var accounts;
//Register
router.get('/register', function(req,res){
res.render('register');
});
//CHAT
router.get('/chat', ensureAuthenticated, (req,res)=>{
console.log(request.body.user.id);
res.render('chat');
});
module.exports=router;
Having checked carefully, this line here in your request from client is the cause fetch("/myurl",{ ...
If you see the guide at MDN, the usage is fetch('http://example.com/movies.json'). Fetch API expects complete url/uri along with the protocol (http, https) etc.
So your request should be like:
fetch("http://yourdomain.com", { ...

Categories