React gives me Cannot GET / page_name While reloading (node/express) - node.js

I am trying to build a reactjs app and I am trying to pass data through from my front end (react) to my backend (node/express). However I am getting an error when I try and view the page I get this error. (Cannot GET /home).
const express = require("express");
const app = express();
const port = 5000;
const cors = require("cors");
app.use(cors());
var bodyParser = require("body-parser");
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(
bodyParser.urlencoded({
// to support URL-encoded bodies
extended: true
})
);
app.post("/home", (req, res) => {
const data = [(generalDetail = req.body.generalDetail)];
console.log(generalDetail, "has been added to /home");
res.json(data);
});
app.listen(port, () => `Server running on port ${port}`);
here is my onSubmit function:
onSubmitForm = e => {
e.preventDefault();
let data = {
generalDetail: this.state.generalDetails,
firstName: this.state.firstName,
middleName: this.state.middleName,
lastName: this.state.lastName
};
axios.post("http://localhost:5000/home", data).then(() => {
//do something
}).catch(() => {
console.log("Something went wrong. Plase try again later");
});

You dont have a get route for home, that is why you are having trouble.
Add the following code above your post route.
app.get("/home", (req, res) => {
console.log("here");
});

Related

Returning data to a user from an external API

i am trying to return the value of my search after using the node-spotify-api package to search for an artist.when i console.log the spotify.search ..... without the function search function wrapped around it i get the values on my terminal..what i want is when a user sends a request to the userrouter routes i want is to display the result to the user..i using postman for testing ..
This is the controller
const Spotify = require('node-spotify-api');
const spotify = new Spotify({
id: process.env.ID,
secret: process.env.SECRET,
});
const search = async (req, res) => {
const { name } = req.body;
spotify.search({ type: 'artist', query: name }).then((response) => {
res.status(200).send(response.artists);
}).catch((err) => {
res.status(400).send(err);
});
};
module.exports = {
search,
};
**This is the route**
const express = require('express');
const searchrouter = express.Router();
const { search } = require('./spotify');
searchrouter.route('/').get(search);
module.exports = searchrouter;
**This is my server.js file**
const express = require('express');
require('express-async-errors');
const app = express();
require('dotenv').config();
// built-in path module
const path = require('path');
// port to be used
const PORT = process.env.PORT || 5000;
// setup public to serve staticfiles
app.use(express.static('public'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.set('port', PORT);
const searchrouter = require('./route');
app.use('/search', searchrouter);
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'index.html'));
});
app.listen(PORT, (req, res) => {
console.log(`Server is listening on port ${PORT}`);
});
[that is my project structure][1]
Well Your Code has a bug
Which is
searchrouter.route('/').get(search);
You are using a get request and still looking for a req.body
const { name } = req.body;
name is going to equal to = undefined
and when this runs
spotify.search({ type: 'artist', query: name })
it's going to return an empty object or an error
req.body is empty for a form GET request
So Your fix is
change your get request to a post
searchrouter.route('/').post(search);

I want to be redirected to a file.js after when i am logged in

This is my Express code by using handlebars using .hbs code
const express = require("express");
const path = require("path");
const app = express();
const port = 3001;
//for mongo all mongodata
require("dotenv").config();
const cors = require("cors");
app.use(cors());
const Handle = require("./views/mongoschema");
const staticPath= path.join(__dirname, "./views");
app.set("view engine","hbs");
app.use(express.static(staticPath));
//for maintaining the format
app.use(express.json());
//to GET the data in the from the form
app.use(express.urlencoded({extended:false}));
//to render the page this is coming (1st)
app.get("/",(req, res) => {
res.render('index');
});
//for login validation
app.post("/mongoschema",async(req, res) => {
try {
const handleData = new Handle({
title: req.body.one,
description: req.body.two,
url: req.body.four
})
const handled = await handleData.save();
//After REGISTRATION sending the user to index file
***res.status(201).render("index");***
} catch (error) {
res.status(400).send(error);
}
});
app.get("/pages", (req, res) => {
Handle.find({})
.then((items) => res.json(items))
.catch((err) => console.log(err));
});
app.listen(port, () => {
console.log('listening to the port ${port)');
});
the file i want to run now is a "file.js" and index is "index.hbs" it is not able to render the "file.js" how can i render or i will be redirected to the "file.js" file After when my login is SUCCESSFUL.
As someone mentioned in the comments, you should be using:
res.redirect("/"); // path to route as parameter - in this case, index.

How to Make API calls in express server

I am trying to make a get request in an express server, currently the server simply prints all post requests and it works fine up to that, the issue is when GET request is made the response is returned as 'undefined'
var env = process.env.NODE_ENV || "development";
var config = require("./config")[env];
const express = require("express");
const bodyParser = require("body-parser");
const axios = require("axios");
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const hostname = config.server.host;
const port = config.server.port;
app.post("/", (req, res) => {
console.log(req.body);
res.sendStatus(200);
axios
.get("https://reqres.in/api/products/3")
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error.response);
});
});
app.listen(port, hostname, () =>
console.log(`Server running at http://${hostname}:${port}/`)
);
Use Postman to send Api calls to the server. I am attaching the link down below.
Install Postman chrome extension, if you're using chrome.
Use the Localhost:port server and post method and add variable to post your query
Hope this helps.
Moreover, Just add this tweak in your code and listen on a proper localhost,
var env = process.env.NODE_ENV || "development";
var config = require("./config")[env];
const express = require("express");
const bodyParser = require("body-parser");
const axios = require("axios");
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const hostname = config.server.host;
const port = config.server.port;
app.post("/", (req, res) => {
console.log(req.body);
res.sendStatus(200);
axios
.get("https://reqres.in/api/products/3")
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error.response);
});
});
app.listen(1337, function(){
console.log('Express listening on port', this.address().port);
});
Executed the below code
axios .get("https://reqres.in/api/products/3")
.then(response => { console.log(response); })
.catch(error => { console.log(error.response); })
Its executed and working fine.
My Guess is that in your case its going to catch block
Change the following line
.catch(error => {
console.log(error.response);
});
TO
.catch(error => {
console.log(error);
});
And see whether some error is printing.No response object is assigned to error, that may be u r receiving undefined

Can't use axios to get/post data from/to localhost server in android 7.0 device - React Native app

I use Axios in my react native app. I use Mobiistar Zumbo J2 with Expo to test but I get err: Network Error. I also set CORS for my node server but it still doesn't work. I test with Postman it work normally. Here is my code:
server.js
const express = require("express");
const path = require("path");
const bodyParser = require("body-parser");
const index = require("./routes/index");
const bookings = require("./routes/bookings");
const cors = require('cors'); // Yep, you need to install this
const app = express();
const port = process.env.PORT || 3000;
app.use(cors());
app.listen(port, () => {
console.log('Server is running on port', port);
});
app.set("views", path.join(__dirname, "views"));
app.set("view engine", 'ejs');
app.engine("html", require("ejs").renderFile);
//Body parser MW
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
//Routes
app.use("/", index);
app.use("/api", bookings);
bookings.js
const express = require("express");
const router = express.Router();
const mongojs = require("mongojs");
const db = mongojs("mongodb://<username>:<password>#ds139614.mlab.com:39614/booking-car-app", ["bookings"]);
router.get("/bookings", (req, res, next) => {
db.bookings.find((err, data) => {
if (err) {
res.send(err);
}
res.json(data);
});
});
router.post("/bookings", (req, res, next) => {
const booking = req.body;
if (!booking.userName) {
res.status(400);
res.json({err: "Bad data"});
} else {
db.bookings.save(booking, (err, savedBooking) => {
if (err) {
res.send(err);
}
res.json(savedBooking);
})
}
})
module.exports = router;
using Axios to get data from server
axios.get("http://127.0.0.1:3000/api/bookings/")
.then(res => {
console.log("Get booking info: ", res);
alert(res);
})
.catch(err => console.log(err))
Error:
Network Error
Stack trace:
node_modules\axios\lib\core\createError.js:16:24 in createError
node_modules\axios\lib\adapters\xhr.js:87:25 in handleError
node_modules\event-target-shim\lib\event-target.js:172:43 in dispatchEvent
node_modules\react-native\Libraries\Network\XMLHttpRequest.js:578:29 in setReadyState
node_modules\react-native\Libraries\Network\XMLHttpRequest.js:392:25 in __didCompleteResponse
node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:191:12 in emit
node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:349:47 in __callFunction
node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:106:26 in <unknown>
node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:297:10 in __guard
node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:105:17 in callFunctionReturnFlushedQueue
...
Please help me.
Thank you very much
Android uses a special type of IP address 10.0.2.2
axios.get("http://10.0.2.2:3000//api/bookings/")
.then(res => {
console.log("Get booking info: ", res);
alert(res);
})
.catch(err => console.log(err))

Cant set headers after they are sent

I am using express backend with a react frontend everything is working fine but occasionally i get error
Cant set header after they are sent
and server gets down.i searched few ways this error might happen but in my code i could not find such cases.i tried to be simple as possible in the code.can anyone please point me what might be the issue?
Server.js file
// call the packages we need
const addItem = require('./controllers/addItem');
const addCategory = require('./controllers/addCategory');
const addSubCategory = require('./controllers/addSubCategory');
const getSubCategory = require('./controllers/getSubCategoryByCategory');
const getCategory = require('./controllers/getAllCategory');
const getAllItems = require('./controllers/getAllItems');
const cors = require('cors');
const express = require('express');
// call express
const app = express(); // define our app using express
const bodyParser = require('body-parser');
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
const port = process.env.PORT || 8080; // set our port
// ROUTES FOR OUR API
// =============================================================================
const addItemRoute = express.Router(); // get an instance of the express Router
const getCategoryRoute = express.Router();
const addCategoryRoute = express.Router();
const addSubCategoryRoute = express.Router();
const getSubCategoryRoute = express.Router();
const getAllItemsRoute = express.Router();
getCategoryRoute.get('/get_category', (req, res) => {
getCategory(res);
});
addCategoryRoute.post('/add_category', (req, res) => {
addCategory(req.body.name, res);
});
getSubCategoryRoute.get('/get_subcategory/:catId', (req, res) => {
getSubCategory(req.params.catId, res);
});
addSubCategoryRoute.post('/add_subcategory', (req, res) => {
addSubCategory(req.body.name, req.body.cat_id, res);
});
// code, name, quantity, length, description and subcategory id should be passed as parameters
addItemRoute.post('/add_item', (req, res) => {
addItem(req.body.item, res);
});
getAllItemsRoute.get('/get_items', (req, res) => {
getAllItems(res);
});
// more routes for our API will happen here
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', addItemRoute);
app.use('/api', getCategoryRoute);
app.use('/api', addCategoryRoute);
app.use('/api', addSubCategoryRoute);
app.use('/api', getSubCategoryRoute);
app.use('/api', getAllItemsRoute);
// START THE SERVER
// =============================================================================
app.listen(port);
console.log(`Server started on port ${port}`);
getAllCategories() function
Object.defineProperty(exports, '__esModule', {
value: true,
});
const pool = require('./connection');
module.exports = function (res) {
pool.getConnection((err, connection) => {
if (err) {
connection.release();
return res.json({ code: 100, status: 'Error in connection database' });
}
console.log(`connected as id ${connection.threadId}`);
connection.query('select * from category;', (err, rows) => {
connection.release();
if (!err) {
return res.json(rows);
}
});
connection.on('error', err => res.json({ code: 100, status: 'Error in connection database' }));
});
};
If you get an error in connection.query() you send a response with res.json(). This error is caught in connection.on('error') where you send another response. You can't send two responses to the same request. It seems that in this case, you don't really need connection.on() at all or if you have it to catch other errors, don't send a response on connection.query()'s error.

Resources