I am attempting to make an axios call inside of a useEffect hook, but all that is returned is the html.index file. I understand that express will direct any calls to "/" to index.html but i have specific routes established and other safeguards in place, so i dont know why this is happening...
React Component:
import React, { Fragment, useState, useEffect } from "react";
//uuid for card element key
import { v4 as uuidv4 } from "uuid";
import API from "../utils/API";
//dummy data
import books from "../dummy.json";
//import components
import Card from "../components/Card";
import Searchbar from "../components/Searchbar";
const Bookshelf = () => {
useEffect(() => {
loadBooks()
});
const loadBooks = () => {
API.getAllBooks().then(res => console.log(res))
}
const [bookArray, setBookArray] = useState({
books,
});
return (
<Fragment>
<div className="bookshelf">
<Searchbar />
<div className="bookshelf__heading__container">
<h2 className="bookshelf__heading">
Release the Kraken of Knowledge!
</h2>
</div>
<div className="bookshelf__container">
<section className="bookshelf__gallery">
{bookArray.books.map((book) => (
<Card
key={uuidv4()}
title={book.title}
author={book.author}
image={book.image}
/>
))}
</section>
</div>
</div>
</Fragment>
);
};
export default Bookshelf;
My Express Server:
const express = require("express");
const PORT = process.env.PORT || 3306;
const app = express();
const { sequelize } = require("./models");
const authors = require("./routes/authors");
const books = require("./routes/books");
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"))
}
app.use("/api/authors", authors);
app.use("/api/books", books);
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "../client/build/index.html"));
});
sequelize.sync().then(() => {
app.listen(PORT, () => {
console.log(listening on ${PORT});
});
});
Axios call:
import axios from "axios";
export default {
getAllBooks: function(){
return axios.get("/api/books/all");
}
};
My routes:
const express = require("express");
const router = express.Router();
const { Op, json } = require("sequelize");
const { Author, Book } = require("../models");
//POST new book:
router.post("/add_book", (req, res) => {
Book.create(req.body)
.then((book) => {
res.status(200).json({ book });
})
.catch((err) => {
res.status(500).send(err);
});
});
//PUT edit book by id:
router.put("/edit/:id", (req, res) => {
Book.update(req.body, {
where: {
id: req.params.id,
},
})
.then((numChanged) => {
res.status(200).json({ changedRows: numChanged[0] });
})
.catch((err) => {
res.status(500).send(err);
});
});
//GET all books;
router.get("/all", (req, res) => {
Book.findAll({
include: [Author],
})
.then((books) => {
res.status(200).json(books);
return json(books)
})
.catch((err) => {
res.status(500).send(err);
});
});
//GET books by title:
router.get("/title/:title", (req, res) => {
Book.findOne({
where: {
title: req.params.title,
},
include: [Author],
})
.then((books) => {
res.status(200).json(books);
})
.catch((err) => {
res.status(500).send(err);
});
});
//GET books by title OR author:
router.get("/search/:search_term", (req, res) => {
Book.findAll({
include: [Author],
where: {
[Op.or]: [
{ title: { [Op.substring]: req.params.search_term } },
{ "$Author.firstName$": { [Op.substring]: req.params.search_term } },
{ "$Author.lastName$": { [Op.substring]: req.params.search_term } },
],
},
})
.then((result) => {
res.status(200).json(result);
})
.catch((err) => {
res.status(500).send(err);
});
});
//DELETE book by id:
router.delete("/book_id/:id", (req, res) => {
Book.destroy({
where: {
id: req.params.id,
},
})
.then((wasDeleted) => {
res.status(200).json({ deleted: wasDeleted !== 0 });
})
.catch((err) => {
res.status(500).send(err);
});
});
module.exports = router;
I also have a proxy server set up and as far as i can tell thats working, but perhaps it might be related somehow...
Please let me know what else i can provide to help figure this out, its driving me up the wall.
EDIT: So if i make the call and include http://localhost:8080/etc, it works. That tell me there is (probably) a problem with the proxy server not working or express not finding it whatever...
Related
i have been doing a postman POST request, but i got an error.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /bookstore</pre>
</body>
</html>
here is my POST request code:
app.post("/bookstore", (req, res) => {
const books = req.body;
db.collection("bookstore")
.insertOne(books)
.then((result) => res.json(result))
.catch((err) => res.send(err));
});
GET request is working normally, but when it came to POST, it is giving an error. Please fix my mistake! Thank you...
here is my full code:
db.js
const { MongoClient } = require("mongodb");
let dbConnection;
module.exports = {
connectToDb: (cb) => {
MongoClient.connect("mongodb://localhost:27017/bookstore")
.then((res) => {
dbConnection = res.db();
return cb();
})
.catch((error) => {
console.log(error);
return cb(error);
});
},
getDb: () => dbConnection,
};
and my index.js:
const express = require("express");
const { connectToDb, getDb } = require("./db");
const { ObjectId } = require("mongodb");
const e = require("express");
// init app and middleware
const app = express();
app.use(express.json());
//db connection
let db;
connectToDb((xato) => {
if (!xato) {
app.listen(3000, () => {
console.log("The 3000 port is installed");
});
db = getDb();
return db;
}
});
//routes
app.get("/bookstore", (req, res) => {
let mybook = [];
// the collection name from mongoDB
db.collection("bookstore")
.find()
.sort({ author: 1 })
.forEach((book) => mybook.push(book))
.then(() => {
return res.json(mybook);
})
.catch(() => {
return res.send("there were an error");
});
// res.json({ MyWords: "I am coming from json res" });
});
app.get("/bookstore/:id", (req, res) => {
if (ObjectId.isValid(req.params.id)) {
db.collection("bookstore")
.findOne({ _id: new ObjectId(req.params.id) })
.then((doc) => res.json(doc))
.catch((err) => res.send(err));
} else {
res.send(" wrong id request");
}
});
app.post("/", (req, res) => {
const books = req.body;
db.collection("bookstore")
.insertOne(books)
.then((result) => res.json(result))
.catch((err) => res.send(err));
});
I have restarted my express server, but it's still not working
i'm new learner in backend node js ... in my code below i created an API for questions and it contains get,post,delete and edit
i wanted to test it using the extension rest client in VS code but when i type Get http://localhost:3000/api in route.rest file to test it,it stucks on waiting
is there a way to know if my API works good and can somebody please help me if i have mistake below?
thanks in advance
//server.js
// #ts-nocheck
const express = require('express');
const morgan = require('morgan');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const jwt = require('jsonwebtoken');
const questionRoutes = require('./routes/subscribers');
const cors = require('cors');
const http = require('http');
// Has to be move but later
const multer = require("multer");
const Question = require('./models/subscriber');
// express app
const app = express();
// Explicitly accessing server
const server = http.createServer(app);
// corsfffffffff
app.use(cors());
dotenv.config();
const dbURI = process.env.MONGO_URL || "mongodb://localhost:27017/YourDB";
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(result => server.listen(process.env.PORT || 3000) )
.catch(err => console.log(err));
// register view engine
app.set('view engine', 'ejs');
app.use(express.json);
// middleware & static files
app.use(express.static('public'));
app.use(express.urlencoded({ extended: true }));
app.use(morgan('dev'));
app.use((req, res, next) => {
res.locals.path = req.path;
next();
});
// routes
// question routes
app.use('/questions' , questionRoutes );
// 404 page
app.use((req, res) => {
res.status(404).render('404', { title: '404' });
});
//questionRoute.js
const express = require('express');
const questionController = require('../controllers/questionCon');
const questionApiController = require('../controllers/questionApiController');
const router = express.Router();
// API Routing
router.get('/api/', questionApiController.get_questions);
router.post('/api/add', questionApiController.create_question);
router.get('/api/:id', questionApiController.get_question);
router.delete('/api/delete/:id', questionApiController.delete_question);
router.put('/api/update/:id', questionApiController.update_question);
// EJS Routing for GUI
router.get('/create', questionController.question_create_get);
router.get('/', questionController.question_index);
router.post('/', questionController.question_create_post);
router.get('/:id', questionController.question_details);
router.delete('/:id', questionController.question_delete);
module.exports = router;
//question.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const questionSchema = new Schema({
questionTitle: {
type: String,
required: true,
},
description: {
type: String,
},
price: {
type: Number,
},
});
const Question = mongoose.model('Question', questionSchema);
module.exports = Question;
//questionAPIcontroller
const Question = require('../models/subscriber');
const validators = require('../validators');
let questionApiController = {
// Get a single question
get_question : async (req , res) => {
const id = req.params.id;
try {
const question = await Question.findById(id,(err, question) => {
if (err) return res.status(400).json({response : err});
res.send("hello")
res.status(200).json({response : question})
console.log("hello")
})
} catch (err) {
res.status(400).json(err);
}
},
// Get all the questions
get_questions: async (req , res) => {
try {
const questions = await Question.find((err, questions) => {
if (err) return res.status(400).json({response : err});
res.status(200).json({response : questions})
})
} catch (err) {
res.status(400).json(err);
}
},
// Create a question
create_question : async (req , res) => {
const {error} = validators.postQuestionValidation(req.body);
if(error) return res.status(400).json({ "response" : error.details[0].message})
try {
const question = await new Question(req.body);
question.save((err, question) => {
if (err) return res.status(400).json({response : err});
res.status(200).json({response : " Question created Successfully"})
});
} catch (err) {
res.status(400).json(err);
}
},
// Delete question
delete_question : async (req , res) => {
const id = req.params.id;
var questionExist = false;
var userId ;
const question = await Question.findById(id).then(result => {
questionExist = true;
userId = result.owner;
}).catch(err => {
questionExist = false;
res.status(400).json({response : err });
});
if(questionExist){
try {
Question.findByIdAndRemove(id ,(err, question) => {
// As always, handle any potential errors:
if (err) return res.json({response : err});
// We'll create a simple object to send back with a message and the id of the document that was removed
// You can really do this however you want, though.
const response = {
message: "Question successfully deleted",
id: question._id
};
return res.status(200).json({response : response });
});
} catch (err) {
res.status(400).json(err);
}
}
else {
return res.status(400).send( { "response" : "A question with that id was not find."});
}
},
// Update question
update_question : async (req , res) => {
const id = req.params.id;
Question.findByIdAndUpdate(id,req.body,
function(err, result) {
if (err) {
res.status(400).json({response : err});
} else {
res.status(200).json({response : "Question Updated"});
console.log(result);
}
})
},
// Get question's questions
}
module.exports = questionApiController
//questionController
const Question = require('../models/subscriber');
const question_index = (req, res) => {
Question.find().sort({ createdAt: -1 })
.then(result => {
res.render('index', { questions: result, title: 'All questions' });
})
.catch(err => {
console.log(err);
});
}
const question_details = (req, res) => {
const id = req.params.id;
Question.findById(id)
.then(result => {
res.render('details', { question: result, title: 'Question Details' });
})
.catch(err => {
console.log(err);
res.render('404', { title: 'Question not found' });
});
}
const question_create_get = (req, res) => {
res.render('create', { title: 'Create a new question' });
}
const question_create_post = (req, res) => {
const question = new Question(req.body);
question.save()
.then(result => {
res.redirect('/questions');
})
.catch(err => {
console.log(err);
});
}
const question_delete = (req, res) => {
const id = req.params.id;
Question.findByIdAndDelete(id)
.then(result => {
res.json({ redirect: '/questions' });
})
.catch(err => {
console.log(err);
});
}
module.exports = {
question_index,
question_details,
question_create_get,
question_create_post,
question_delete
}
change code
app.use(express.json);
to
app.use(express.json());
I am making a simple Walk-In register app where i will register a customer and then find that specific customer by their phone number. The registration part is done but i cannot get a customer by their phone number. A little help will be very much appreciated. Below im posting both my backend and frontend code.
API-Server.js
const express = require('express');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const cors = require('cors')
const customerRouter = require('./routes/customer');
const app = express();
const port = process.env.PORT || 5000;
dotenv.config();
app.use(cors())
app.use(express.json());
app.use('/api/customer', customerRouter);
mongoose
.connect(process.env.MONGO_URI)
.then((data) => {
console.log(
'MongoDb connected successfully....'
);
})
.catch((err) => {
console.log(err);
});
app.listen(port, () => {
console.log(`Server is running at Port ${port}`);
});
API - customerRoute.js
const router = require('express').Router();
const Customer = require('../models/Customer');
router.post('/add', (req, res) => {
const newCustomer = new Customer({
name: req.body.name,
phone: req.body.phone,
address: req.body.address,
pin: req.body.pin,
});
newCustomer
.save()
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error creating a new customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
router.get('/', (req, res) => {
Customer.find()
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error getting customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
router.get('/getbyphone', (req, res) => {
Customer.findOne({ phone: req.body.phone })
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error getting customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
router.get('/getbyname', (req, res) => {
Customer.findOne({ name: req.body.name })
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error getting customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
module.exports = router;
Frontend - App.js
import { BrowserRouter as Router } from 'react-router-dom';
import { Route } from 'react-router-dom';
import Navbar from './components/Navbar';
import Search from './components/Search';
import Submit from './components/Submit';
function App() {
return (
<Router>
<div className='App'>
<Navbar />
<Route path='/' exact component={Submit} />
<Route path='/view' component={Search} />
</div>
</Router>
);
}
export default App;
frontend - search.js
import axios from 'axios';
import React, { Component } from 'react';
export default class Search extends Component {
constructor() {
super();
this.state = {
phone: '',
};
}
onPhoneChange = (event) => {
this.setState({
phone: event.target.value,
});
};
handleSubmit = (event) => {
event.preventDefault();
console.log(this.state.phone);
axios
.get(
'http://localhost:5000/api/customer/getbyphone',
this.state.phone
)
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
this.setState({
phone: '',
});
};
render() {
return (
<div>
<h3>Search for a Customer</h3>
<form
onSubmit={this.handleSubmit}
className='form-control form-control-sm'>
<div className='form-group'>
<label>Phone: </label>
<input
type='text'
required
className='form-control'
onChange={this.onPhoneChange}
value={this.state.phone}
/>
</div>
<div className='form-group'>
<input
type='submit'
className='btn btn-primary'
value='Search Customer'
/>
</div>
</form>
</div>
);
}
}
you could change this route and read phone number from params
router.get('/getbyphone/:phone', (req, res) => {
Customer.findOne({ phone: req.params.phone }) // change this line
.then((cx) => {
if (!cx) {
res
.status(400)
.send('Error getting customer');
} else {
res.send(cx);
}
})
.catch((err) => {
res.status(500).json({ err });
});
});
and change the react part like this
handleSubmit = (event) => {
event.preventDefault();
console.log(this.state.phone);
axios
.get(
'http://localhost:5000/api/customer/getbyphone'+this.state.phone /// change this line
)
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
this.setState({
phone: '',
});
};
I set up a proxy to bypass CORS for the intended api in this react application. I'm having trouble to pass data from react component to proxy(nodeJS server). I've read a few links such as here and here but still have no clues.
/*React component*/
import React, { useState } from "react";
import axios from "axios";
export default function Mail() {
const [emailInput, setEmailInput] = useState('')
const getMail = () => {
axios.get("/list/members").then(json => {
console.log(json.data);
});
};
const subscribe = (email) => {
console.log('inside subscribe')
axios.post("/member", email)
.then(data => console.log('post succeeds'))
.catch(err => console.log(err))
}
const handleSubmit = e => {
e.preventDefault();
const email = {
email_address: `${emailInput}`,
status: "subscribed"
};
subscribe(email)
};
const handleChange = (e) => {
setEmailInput(e.target.value)
}
return (
<form onSubmit={handleSubmit}>
<input type="text" name="email" placeholder="enter your email" value={emailInput} onChange={handleChange}/>
<input type="submit" value="subscribe" />{" "}
</form>
);
}
In node server, I have
app.post("/member", (req, res) => {
const email = {
email_address: "axios1234#gmail.com",
status: "subscribed"
};
axios.post(
"https://<apilink>",
email,
{
withCredentials: true,
auth: {
username: "anystring",
password: "<apikey>"
}
}
).then(json => {
res.send(json.data)
}).catch(err => {
console.log(err);
})
});
I've checked that my conduit between react front end app and proxy server is working. I also examined both req and res in app.post("/member", (req, res) but found thatreq.body is undefined and couldn't find the email object that was passed in from react function component. Did I miss anything here?
Are you using a body-parser? If not, install body-parser and then change your code to this:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post("/member", (req, res) => {
const email = req.body.email_address;
axios.post(
"https://<apilink>",
email,
{
withCredentials: true,
auth: {
username: "anystring",
password: "<apikey>"
}
}
).then(json => {
res.send(json.data)
}).catch(err => {
console.log(err);
})
});
I have created the backend operations using Node.js / MongoDB and created services for them, but when I run the server it indicates that I've connected successfully, but I can't see a database in Robo 3T.
Here is what I coded:
DBConfig.js
var mongoose = require ('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
name : {
type : String,
require : true
},
address : {
type : String,
require : true
}
});
mongoose.model("User", UserSchema);
module.exports = mongoose;
mongoose.connect('mongodb://127.0.0.1:27017/TestDB4', function(err){
if(err)
{
console.log(err);
process.exit(-1);
}
console.log("Connected to the db")
});
I can't see an error. Why isn't the DB created?
check your User.Controller.js as this below,
var mongoose = require('../DBSchema/SchemaMapper');
var UserSchema = mongoose.model('User');
var UserController = function(){
this.insert = (data) => {
return new Promise((resolve, reject) => {
var user = new UserSchema({
userName: data.userName,
password: data.password
});
user.save().then(() => {
resolve({status: 200, message: "Added new user"});
}).catch(err => {
reject({status: 500, message: "Error:- "+err});
})
})
}
this.update = (id, data) => {
return new Promise((resolve, reject) => {
UserSchema.update({_id: id}, data).then(() => {
resolve({status: 200, message: "update user"});
}).catch(err => {
reject({status: 500, message: "Error:- " + err});
})
})
}
this.searchAll = () => {
return new Promise((resolve, reject) => {
UserSchema.find().exec().then((data) => {
resolve({status: 200, data: data});
}).catch(err => {
reject({status: 500, message: "Error:- " + err});
})
})
}
this.search = (id) => {
return new Promise((resolve, reject) => {
UserSchema.find({_id:id}).exec().then(user => {
resolve({status: 200, data: user});
}).catch(err => {
reject({status: 500, message: "Error:- " + err});
})
})
}
this.delete = (id) => {
return new Promise((resolve, reject) => {
UserSchema.remove({_id:id}).then(() => {
resolve({status: 200, message: "remove user"});
}).catch(err => {
reject({status: 500, message:"Error:- " + err});
})
})
}
}
module.exports = new UserController();
And User.Route.js as below,
var express = require('express');
var router = express.Router();
var Controller = require('./User.Controller');
router.post('/', (req, res) => {
Controller.insert(req.body).then(data => {
res.status(data.status).send({message: data.message});
}).catch(err => {
res.status(err.status).send({message: err.message});
})
});
router.put('/:id', (req, res) => {
Controller.update(req.params.id, req.body).then(data => {
res.status(data.status).send({message: data.message});
}).catch(err => {
res.status(err.status).send({message: err.message});
})
});
router.get('/', (req, res) => {
Controller.searchAll().then(data => {
res.status(data.status).send({data: data.data});
}).catch(err => {
res.status(err.status).send({message: err.message});
});
});
router.get('/:id', (req, res) => {
Controller.search(req.params.id).then(data => {
res.status(data.status).send({data: data.data});
}).catch(err => {
res.status(err.status).send({message: err.message});
});
});
router.delete('/:id', (req, res) => {
Controller.delete(req.params.id).then(data => {
res.status(data.status).send({message: data.message});
}).catch(err => {
res.status(err.status).send({message: err.message});
})
})
module.exports = router;
check your app.js as follows
const Express = require("express");
const BodyParser = require("body-parser");
const Routes = require("./Routes");
const Cors = require("cors");
const app = Express();
app.use(Cors());
app.use(BodyParser.urlencoded({ extended: false }));
app.use(BodyParser.json());
app.use('/', Routes);
app.listen(8083, 'localhost', (err) => {
if(err) {
console.log(err);
process.exit(-1);
}
console.log("Server listen port 8083");
});
and Routes.js as follows,
var Express = require("express");
var Routes = Express.Router();
var UserRoute = require('./src/User/User.Route');
var CommentRoute = require('./src/Comment/Comment.Route');
Routes.use('/user/', UserRoute);
Routes.use('/comment/', CommentRoute);
module.exports = Routes;