I want to search for my product to display on my browser by clicking the search button.
I can search products by Postman API nicely. But, I have no idea to display data by clicking the search button.
product.js
router.get("/find/:id", async (req, res) => {
try {
const product = await Product.findById(req.params.id);
res.status(200).json(product);
} catch (err) {
res.status(500).json(err);
}
});
//GET ALL PRODUCTS
router.get("/", async (req, res) => {
const qNew = req.query.new;
const qCategory = req.query.category;
try {
let products;
if (qNew) {
products = await Product.find().sort({ createdAt: -1 }).limit(1);
} else if (qCategory) {
products = await Product.find({
categories: {
$in: [qCategory],
},
});
} else {
products = await Product.find();
}
res.status(200).json(products);
} catch (err) {
res.status(500).json(err);
}
});
Navbar.js
const Navbar = () => {
return (
<Button>Search</Button>
);
};
export default Navbar;
You're going to want to use Axios to make a request from your react application.
To do this you need to install and require Axios into your react application.
This code will allow you to make a request to your express application:
async function getProduct(productID) {
try {
const response = await axios.get(`/find/${productID}`);
console.log(response);
} catch (error) {
console.error(error);
}
}
This is going to only work when you know what the ID of the product you're searching is. If you have another endpoint on your server to search for a product via name you can change the endpoint accordingly. Here are the Axios docs.
Hope this helps. Thanks!
Related
Node.js CODE
exports.user = async (req, res) => {
try {
const { wallet } = req.body;
if (!wallet) {
res.status(400).json({ error: "Not logged in" });
return;
} else {
user = User.findone(wallet);
// if user is not found then create a new user and mark as loggged In
if (!user) {
User.create({
user: wallet,
});
}
// if user found then create a session token and mark as logged
in
res.send({
user: wallet,
});
}
} catch (error) {
console.log(`ERROR::`, error);
}
};
REACTJs CODE
// post call/update
const axiosCall = async () => {
// core login will give a unique username by fulling a transcation
// core.login i dont have any control
const userAccount = await core.login();
try {
const res = await Axios.post(`${API}/user`, userAccount, dataToken);
setData({
...data,
error: "",
success: res.data.message,
});
} catch (error) {
setData({
...data,
error: error.response.data.error,
});
}
};
Now here the problem occurs when some one could modify userAccount in the front-end or someone could send a body with wallet: anything to my route localhost:3000/api/user
There is no option for me to check if some actually used core.login(); to get the wallet address.
So is there any solution?
I was thinking to allow only my server IP or localhost to hit the route localhost:3000/api/user and is that even possible?
Also there is another issue anyone could modify userAccount in front-end.
I make a crud with products
I send an http request to the /api/deleteProduct route with the product id to retrieve it on the server side and delete the product by its id
To create a product it works only the delete does not work
pages/newProduct.js :
useEffect(() => {
async function fetchData() {
const res = await axios.get('/api/products');
setProducts(res.data);
}
fetchData();
}, []);
const handleSubmit = async (event) => {
event.preventDefault();
const formData = new FormData();
formData.append('picture', picture);
formData.append('name', name);
formData.append('price', price);
formData.append('category', category);
formData.append('description', description);
try {
const res = await axios.post('/api/createProduct', formData);
console.log(res.data);
} catch (error) {
console.log(error);
}
};
const handleDelete = async (id) => {
try {
await axios.delete(`/api/deleteProduct?id=${id}`);
setProducts(products.filter(product => product._id !== id));
} catch (error) {
console.log(error);
}
};
api/deleteProduct.js :
import Product from '../../models/Products';
import { initMongoose } from '../../lib/mongoose';
initMongoose();
export const handleDelete = async (req, res) => {
if (req.method === 'DELETE'){
try {
const { id } = req.params
const product = await Product.findByIdAndRemove(id);
if (!product) {
return res.status(404).json({ message: 'Product not found' });
}
return res.status(200).json({ message: 'Product deleted successfully' });
} catch (error) {
console.log(error);
return res.status(500).json({ message: 'Database error' });
}
}};
I have a 500 error but no error in the server side console and the console.log is not showing like the file was not read
Based on the code you've shared, it seems that the problem may be with the way that the delete request is being handled on the frontend. Specifically, in this line:
await axios.delete("/api/deleteProduct", { params: { id } });
The delete request is supposed to receive the id of the product that should be deleted as a query parameter, but it is being passed as a request body.
Instead of passing it as a parameter, you should pass it as a query parameter by changing it to
await axios.delete(`/api/deleteProduct?id=${id}`);
Also, in your api/deleteProduct.js, you should change the following line:
const { id } = req.query;
to
const { id } = req.params;
Also, you should make sure that the server is running and that the api endpoint '/api/deleteProduct' is accessible and handling the request correctly.
For the last, make sure that the product model is imported and initialized correctly and the database connection is established.
Hope that it solves your problem or, at least, helps :))
I succeeded, I put this (server side):
const { id } = req. query;
and (client side):
await axios.delete(/api/deleteProduct?id=${id});
and I exported my function like this:
export default async function handleDelete(req, res) {
Problem: So I'm trying to integrate MongoDB into my nextJs project. Here's a library file which connects to the database.
import shopSchema from './Schemas/shopSchema';
let shopModelCached;
async function getShopModel(connectionUrl) {
if (!shopModelCached) {
try {
await mongoose.connect(process.env.MONGO_DB_CONNECTION_STRING);
const Shop = mongoose.model("shop", shopSchema);
shopModelCached = Shop;
} catch (err) {
throw err;
}
}
return shopModelCached;
}
export default getShopModel;
When I call the function to get the shop model on my getServerSidedProps on my page, which does literally nothing but call the above function to get the Shop model, and then performs simple query to populate the props.
export async function getServerSideProps(context) {
try {
const Shop = await getShopModel(
process.env.MONGO_DB_CONNECTION_STRING
);
const shop = await Shop.findOne({
shopcode: context.params.shopname,
}).exec();
return {
props: {
shop,
},
};
} catch (err) {
throw err;
}
}
This hits me with an error when I recompile modules. It says, 'OverwriteModelError: Cannot overwrite 'shop' model once compiled.'. My approach to handling this was to cache the model so it wouldn't be overwritten, but to no vain.
I have a REST API, shown below, that takes in a code param, search the database, return a result if the param exists, and redirect users to a long_url gotten from the database. How do I translate this to graphQL?
indexRoute.get("/:code", async (req, res) => {
try {
const urlCode = req.params.code
const url = await Model.findUrlCode(urlCode)
if (url) {
return res.redirect(url.long_url)
} else {
return res.status(404).json("No url found.")
}
} catch (err) {
console.log(err)
return res.status(500).json("Server error")
}
})
export default indexRoute
a very good resource with example,
https://blog.bitsrc.io/migrating-existing-rest-apis-to-graphql-2c5de3db
I have been learning firebase firestore functions and I wanted to list all users and have then compare a value to that they have stored. Such as if there are 20 users and I want to see all users named "mike" how can I get an array of the users so I can compare them so I can find all users name "mike"?
I am running:
"firebase-admin": "^5.11.0",
"firebase-functions": "^1.0.0"
I saw this snippet of code for firebase admin but I dont thing it works as it wasn't labeled a firestore function, but if it does if I return the "admin.auth().listUsers..." will I get an arraylist of users?
function listAllUsers(nextPageToken) {
// List batch of users, 1000 at a time.
admin.auth().listUsers(1000, nextPageToken)
.then(function(listUsersResult) {
listUsersResult.users.forEach(function(userRecord) {
console.log("user", userRecord.toJSON());
});
if (listUsersResult.pageToken) {
// List next batch of users.
listAllUsers(listUsersResult.pageToken)
}
})
.catch(function(error) {
console.log("Error listing users:", error);
});
}
This is how I done it:
const functions = require('firebase-functions');
const admin = require('firebase-admin')
admin.initializeApp()
const express = require('express')
const app = express()
app.get('/users', async (req, res) => {
try {
const listUsers = await admin.auth().listUsers()
return res.status(200).send({ listUsers })
} catch (err) {
return handleError(res, err)
}
})
exports.api = functions.https.onRequest(app)
this shows a list of users but still need some work to make it better
Update
exports.getAllUsers = async (req, res) => {
var allUsers = [];
return admin.auth().listUsers()
.then(function (listUsersResult) {
listUsersResult.users.forEach(function (userRecord) {
// For each user
var userData = userRecord.toJSON();
allUsers.push(userData);
});
res.status(200).send(JSON.stringify(allUsers));
})
.catch(function (error) {
console.log("Error listing users:", error);
res.status(500).send(error);
});
}
Maybe you should do that search with the function getUserByDisplayName().
You can see it in this Firebase guide: https://firebase.google.com/docs/auth/admin/manage-users#list_all_users. But as Frank said that has nothing to do with firebase-functions. It is a part of Firebase Auth.
Hope this helps!