Get JSON Object from URL using Express - json

In the express users.js file:
router.get('/', function(req, res, next) {
fetch('https://www.somwhere.com/users')
.then(res => res.json())
.catch(error => console.log(error));
});
module.exports = router;
In my App.js file for my React App I use
componentDidMount() {
fetch('/users')
.then(res => res.json())
.then(users => this.setState({ users }));
}
Right now it throws a 500 error and its not catching the error
Can I get some help fixing this

You can use axios in your FrontEnd("React") and BackEnd("Express"). This code below only an example code that you can follow:
🔴 Backend: Express Server Using axios
const express = require('express');
const app = express();
const axios = require('axios');
const cors = require('cors');
app.use(cors( { origin: '*'}));
const END_POINT = 'https://jsonplaceholder.typicode.com/users';
app.get('/users', async (req, res) => {
try {
const { data } = await axios.get(END_POINT);
res.status(200).send(data);
} catch(ex) {
res.status(500).send(ex.data);
}
})
app.listen(3000, () => {
console.log('Server is up');
});
The code above only an example if you want to using axios in your backend.
📤 Updated: Using fetch
If you still want to using fetch, then you can use code below 👇:
router.get('/', async (req, res) => {
try {
const result = await fetch('https://jsonplaceholder.typicode.com/users');
const json = await result.json();
res.status(200).send(json);
} catch(ex) {
console.log(ex);
res.status(500).send(ex.message);
}
})
module.exports = router;
🔵 FrontEnd: React Using axios
async componentDidMount() {
try {
// change the endpoint with yours
const { data } = await axios.get('http://localhost:3000/users');
console.log(data);
// do some stuff here: set state or some stuff you want
} catch(ex) {
console.log(ex);
}
}
💡 Dont Forget to install and import axios in your React App.
📤 Updated: If you still want to using fetch in your React App, than you can use this code below:
async componentDidMount() {
try {
// change the endpoint with yours
const result = await fetch('http://localhost:3000/users');
const json = await result.json();
console.log(json);
// do some stuff here: set state or some stuff you want
} catch(ex) {
console.log(ex);
}
}
I hope it's can help you 🙏.

Related

How to render to Dom API Array from res.json?

I got some data (articles) from website after scraping with cheerio. I can see it as json file on terminal.
How can I render it to Dom? How can get to see it on the console on the browser?
It's a simple app with only index.js file and at the moment.
Thanks!
I have console log it to terminal like so:
res.json(articles);
console.log(articles)
index.js looks like this:
const PORT = process.env.PORT || 8000;
const express = require("express");
const axios = require("axios");
const cheerio = require("cheerio");
const app = express();
const webpages = [{
name: "ynet",
address: "https://www.ynet.co.il/sport/worldsoccer",
}]
const articles = [];
webpages.forEach(webpage => {
axios
.get(webpage.address)
.then((res) => {
const html = res.data
const $ = cheerio.load(html)
$('div.slotView', html).each(function () {
const title = $(this).text();
const url = $(this).find('a').attr("href");
const img = $(this).find('img').attr('src')
articles.push({
title,
url,
img,
source: webpage.name
});
});
}).catch((err) => console.log(err));
});
app.get("/", (req, res) => {
res.json(articles);
console.log(articles)
})
app.listen(PORT, () => {
console.log(`server runnig on PORT ${PORT}`);
});
I have added an app.js file, querySelector the id from div HTML file, and fetched it like so:
const ynet = document.querySelector('#ynet');
fetch('http://localhost:8000/ynet')
.then(response => response.json())
.then(data => {
data.forEach(element => {
const item = `<a href = "${element.url}" target="_blank"><div class="wrapper"><h3>` +
element.source +
`</h3><p class="text">` +
element.title +
`<img src="${element.img}" alt=""></p></div ></a>`
ynet.insertAdjacentHTML("beforeend", item)
});
console.log(data)
})
.catch(err => {
console.log(err)
})

Getting empty {} from mysql table, on React and node.js

For some reason am getting empty object back from mysql table, the table is filled in with some vacation detail. And i want to display them with map in my react app.
On the client side am doing the request with useEffect state and axios.
useEffect(() => {
axios.get("http://localhost:3001/vacations")
.then((response) => {
let vacationsResponse = response.data;
dispatch({ type: ActionType.GetAllVacations, payload: vacationsResponse })
}).catch(err => {
console.log("Failed to get data" + err)
})
}, [dispatch])
this is the server side:
const vacationsControllers = require("./Controllers/vacationsControllers");
const cors = require("cors");
server.use(cors({ origin: "http://localhost:3000" }));
server.use("/users", usersController);
server.use("/vacations", vacationsControllers);
server.listen(3001, () => console.log("Listening on http://localhost:3001"));
this is the vacationsControllers folder:
router.get("/", async (request, response) => {
let vacationsData = request.body;
try {
await vacationsDao.getAllVacations(vacationsData);
response.json();
console.log(vacationsData) *get this empty in the node terminal*
} catch (e) {
console.error(e);
response.status(600).json();
}
});
module.exports = router;
The sql execute (the vacationDao folder):
let connection = require("./connection-wrapper");
async function getAllVacations(vacationsData) {
const sql = `SELECT * FROM current_deals`;
await connection.executeWithParameters(sql);
return vacationsData;
}
module.exports = {
getAllVacations,
};

webpack-dev-server (devServer) doesn't receive json data (payload) from axios | req.query & req.params are empty

I have a webpack-dev-server config like
const path = require('path')
const CircularJSON = require('circular-json') //just to allow me to log circular references
module.exports = {
...
devServer: {
before(app) {
app.all('/my/route', (req, res) => {
console.log(CircularJSON.stringify(req))//req.query & req.params are empty {}
// I wanna have access to sent payload from Axios here, eg:
const result = {
foo1: req.query.bar1,
foo2: req.query.bar2
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(result));
});
}
}
}
The equivalent axios call is like
axios.post('/my/route', {bar1: 'x', bar2: 'y'}).then(...) => {...})
I'm able to hit the route because I got the console.log(CircularJSON.stringify(req)) output, but the req.query & req.params are empty. I suspect it is due to the fact that I was sending JSON data, but even with extra axios config {headers: { 'Content-Type': 'application/json' }} I couldn't get the data I wanna send.
Any idea ?
the solution was to use 'body-parser'
const path = require('path')
const CircularJSON = require('circular-json') //just to allow me to log circular references
const bodyParser = require('body-parser')
module.exports = {
...
devServer: {
before(app) {
// use bodyParser for axios request
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.all('/my/route', (req, res) => {
console.log(CircularJSON.stringify(req))//req.query & req.params are empty {}
// access them on req.body:
const result = {
foo1: req.body.bar1,
foo2: req.body.bar2
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(result));
});
}
}
}

How to add a users auth in feathers middleware?

I use feathersjs framework in my projekt. In older version my middleware it was work but afer update a framework and after created new app with authenticate a middleware not working.
My index.js file show like below:
const cookieParser = require('cookie-parser');
const { authenticate } = require('#feathersjs/express');
module.exports = function (app) {
app.get('/login', (req, res) => {
res.sender('login');
});
app.use('/', cookieParser(), authenticate('jwt'), async (req, res) => {
const { user } = req;
try {
await app.service('users').get(user._id);
res.sender('home');
} catch(e){
res.redirect('/login');
}
});
}
I have a login script in jQuery like below:
$(document).ready(function(){
const socket = io();
const app = feathers();
app.configure(feathers.socketio(socket));
app.configure(feathers.authentication({
storage: window.localStorage
}));
$('.form-signin').submit(function(){
app.authenticate({
strategy: 'local',
username: $('#inputUsername').val(),
password: $('#inputPassword').val(),
}).then( result => {
document.cookie = "feathers-jwt=" + result.accessToken;
window.location.href = "/";
}).catch(error => {});
});
});
My problem is when I click a login button with a data correctly I receive an accessToken but I can't see home page and app show me every time 401 error code - not authorization with.
An console shows me this info: info: Invalid authentication information (no `strategy` set) {"type":"FeathersError","name":"NotAuthenticated","code":401,"className":"not-authenticated","errors":{}}
In new version not working too failureRedirect: '/login'
SOLUTION
Add below code before app.get('/', authenticate('jwt'), (req, res) => {});
app.use('/', cookieParser(), (req, res, next) => {
var cookies = req.cookies;
var token = cookies['feathers-jwt'];
req.authentication = {
strategy: 'jwt',
accessToken: token
}
next();
})

can´t make your two or more methods in same route

the link to the project
https://github.com/Kammikazy/project
i can´t make work my get two or more methods in same route
i have the code 404
i using mysql nodejs and express
my code
controller alliances
const User = require('../models/Alliances')
const findAlianca = async (connection, req, res) => {
const Allianca = await User.find(connection, req.session.user.username)
if (!Allianca) {
res.status(404).send('Nenhuma cidade encontrada.');
return;
}
console.log("dddd");
req.session.Allianca = Allianca
res.locals.Allianca = Allianca
res.render('Administration/Alliances')
}
module.exports = {
findAlianca
}
route aliance
const express = require('express')
const router = express.Router()
const connection = require('../../Config/database')
const controllerAdmin = require('../../controllers/Administration')
const controlleruser = require('../../controllers/Alliances')
router.get('/Administration/Alliances', (req, res) => controllerAdmin.findcidade3(connection, req, res))
router.get('/Administration/Alliances/limitado', (req, res) => controlleruser.findAlianca(connection, req, res))
module.exports = app => app.use('/', router)
models aliance
const find = (connection,username) => {
return new Promise((resolve, reject) => {
connection.query(SELECT alianca.nome,alianca.N_membros,alianca.TAG FROM user INNER JOIN alianca ON user.cod_alianca=alianca.id WHERE user.username='${username}', (err, result) => {
if(err){
reject(err)
}else{
resolve(result)
}
})
})
}
module.exports = {
find
}
alliance.jade
extends layout
block title
.col-xs-6.col-xs-offset-3.col-sm-6.col-sm-offset-3
.col-sm-4(style='width:76%')
div.panel.panel-primary(style='height:50px') Alliances Page
div.panel.panel-primary(style='height:700px') fdssdklfsdklfjskldfjkldsjfl
if locals.user.cod_alianca==null
p You Dont Have Alliances
else
br
span Your Aliance
span= locals.Allianca.nome
.col-xs-2.panel-red(style='width:24%;height:100%;text-align:center')
my app
require('./routes/Administration/Alliances')(app)
my connection db
const mysql = require('mysql')
const config = require( "./config.json" )
const connection =mysql.createConnection({
host:config.host,
user:config.user,
password:config.password,
database:config.database,
// port:config.port
});
connection.connect((err) =>{
if(err){
console.log(err)
process.exit(0)
}else{
console.log('database on')
}
})
what i doing wrong i can´t find the solution for my problem
Not sure what you are asking however if you want to call multiple function in same route/API you can do following:
Using expressJs you can use next function like:
app.get('/Administration/Alliances', (req, res, next) => {
//Do something here and to add data to your request use
req.body.newData = 'newData';
//after this just call next function
next();
}, (req, res, next) => {
//Can continue this cycle of calling next function until last `sendResponse` function is reached.
//Can even set `error` in request for `sendResponse`
req.error = "Some error";
next();
}, (req, res) => {
if(req.error) {
res.status(400).send(req.error);
} else {
res.status(200).send(req.body.result);
}
});
the soluction for my problem
const express = require('express')
const router = express.Router()
const connection = require('../../Config/database')
const controllerAdmin = require('../../controllers/Administration')
const controlleruser = require('../../controllers/Alliances')
router.get('/Administration/Alliances', (req, res, next) => {
//Do something here and to add data to your request use
controllerAdmin.findcidade3(connection, req, res)
next();
}, (req, res, next) => {
//Can continue this cycle of calling next function until last `sendResponse` function is reached.
//Can even set `error` in request for `sendResponse`
controlleruser.findAlianca(connection, req, res)
})
module.exports = app => app.use('/', router)