i have a mern application in which a person can upload his profile pic. Now once the main page of the app loads i want to show all the users along with their profile picture and a little info. For this to happen the server must return multiple images. How do i achieve this in node js. Sending multiple images to the frontend.
You can send it to the front-end as a JSON response.
Since you didn't provide any code to start with, I assume you are using MongoDB with mongoose.
async function getUsers () {
try{
const data = await User.find()
const users = data.map((user)=> user)
res.json({
users
})
}catch(err){
throw err
}
The piece of code above returns a JSON response with an array of the user objects if, in your database there an image field, you will get it also in the JSON response while fetching it on the front-end.
Related
I have this project I’m working on and I am using node/express + Axios to retrieve data from a third-party API.
I am attaching an image of the response I am getting from my postman but,
I am having an issue figuring out a way to access and manipulate a specific set of data.
If there are any resources anyone could share that would help I would appreciate it.
as of now I just have:
axios.get('apiUrl')
.then((response) => {
const cardData = response.data;
res.send(cardData);
}
This is the response I get:
for example, I’d like to access the “abilities” property.
Since that property is within the “0" object within the response object, I’m a bit confused as to how to navigate this in the code.
I’ve tried response.data.0 but that doesn’t seem to work.
function retrieve(callback){
//I don't get why you are using request.send here. Are you routing the response elsewhere?
//If you are just consuming a service, use Axios with a callback instead.
//If you're not routing it you won't need Express.
axios.get('apiUrl').then(response => callback(response));
}
function clbk(response){
let obj = JSON.parse(response); //In case you are receiving a stringified JSON
//Do whatever you want with the data
//If you have a number as a key, access it by using []. So, considering your example:
response.data[0]
}
//CALL:
retrieve(clbk);
I've set up a react form running on http://localhost:3000/about and I've the backend running on port 5000 (localhost:5000). On react's package.json I set up "proxy":"localhost:5000:.
When I use postman and I send the post to localhost:5000/api/contact, the email is sent correctly (I send the data as JSON - name, email and message). Status 200
When I use the react form, the data is well prepared as json but I can't figure out the baseURL to send correctly the method post. status 404. I tried:
localhost:3000/about/api/contact;
localhost:3000/api/contact;
localhost:3000/api.... None works...
FYI
the server is set up with the following middleware and is working ok:
app.use('/api',contactRoute)
the controller is imported and coded as following:
router.post('/contact', (req, res)=>{
const data = req.body;
The React part is not posting correctly with axios and is coded as following:
onSubmit: async (values) => {
//values.preventDefault();
try {
const data = (JSON.stringify(values, null, 2))
setLoader(true);
console.log(data)
await axios.post('/contact', data);
The method post in react is never completed, when I check the console.log of data, is correctly structured as JSON...status 404
use the post parameter in your axois request {port: 5000} then It will use your actual backend port.
By default, axios uses the base path from the URL. So, here when an API request is made.
await axios.post('/contact', data);
It is actually making the post request on localhost:3000 rather than your backend server at localhost:5000. Also, "api" should also be prepended.
One simple way is to use absolute URL which should work.
await axios.post('http://localhost:5000/api/contact', data);
I am implementing a gallery where i wanted to show all images in a page - Reactjs or Angular
How can i send multiple images to frontend from NODE? I was able to send one image file saved in a folder in nodejs.
Below is the code for sending single image - im able to see that image using POSTMAN
Note : here im fetching the image name from a table - These images are there in event folder(image1.jpg, image2.jpg...)
console.log(req.files);
const {id} = req.params;
var sql = "SELECT image from users_image where id = ?";
var query = db.query(sql, [id], function(err, result) {
if(err){
console.log("Error ", err);
res.status(500).send(err)
} else {
const fileNameAndPath = result[0].image; //image1.jpg
if(err) res.status(500).send(err);
res.sendFile(fileNameAndPath, { root: './public/images/upload_images/event' })
}
});
}
But im not able to send multiple images using sendFile() as it does only single image.
How can i implement this?
is it possible to get the preview using postman if i sent multiple images from node?
I could find many example which reads images from server but to html files in same backend directory. They are not sending the response to frontend, so that we can get the image and show in out ui built in react or angular.
Is my approach correct? Planning to deploy frontend, backend and DB in same server
If I understood correctly, your images are in a folder that is located in your NODE JS backend folder and you want to send multiple images depending on request from your REACT Side.
To do this you can make the folder where you stored those images in backend as a public static folder.
In your entry point of Node Application,
app.use(express.static(__dirname+'/<foldername>'));
Now suppose you have a image inside the folder named flower.jpg, car.png and jolly.jpg that you want to send.
The URL for these images will be :
localhost:<port number>/<image name>
For example :
localhost:3000/car.png
localhost:3000/flower.jpg
Now to access from your react code all you need to do is, replace localhost with the IP of your NodeJS Server.
Something like : 172.32.112.12:3000/car.png
You just need to make sure that the image names are not something common and easy.
My image names are something like 1639873167172-464191690.jpg. I change it while I store it on database.
If the photos are already hosted on your server, you should send an array of urls to the photos. In the frontend, you can loop through the array of urls and display the images using image tags.
Im new in backend development (using NodeJs Express).
Its very basic question (I didn't find any good tutorial about it)
Question is:
I have this line of code:
app.get('/test', function (req ,res){
res.send('test');
});
What I wanna do is: BackEnd only sends res to FrontEnd, if FrontEnd send some JSON first.
Like Backend will show Something to FrontEnd, only if FrontEnd send JSON first;
How to handle it? What code to write?
Or what to type in google search to find this kind of tutorial
You are building a REST API with node. In REST we don't keep states. When we receive a request we process and respond. In the Front end, you can do wait until the response is received. use promises, async-await or callbacks to wait until the response in the Front end. Use these methods to connect with back end from front-end axios, fetch. To process the incoming JSON body use body-parser. Based on the request body you can process and send the response. PS: Every request should be given a response. That's how REST behaves.
In Query
yourbackend.com/test?message=welcomeToStackOverflow
This is how you can access with in query:
const {message} = req.query;
console.log(message);
// welcomeToStackOverflow
In Params
yourbackend.com/test/:message
This is how you can access with in params :
const {message} = req.params;
console.log(message);
// welcomeToStackOverflow
Here you have working example : https://codesandbox.io/s/trusting-rosalind-37brf?file=/routes/test.js
Any help would be hugely appreciated! Been stuck on this for a few days.
I have an Express/Next.js app where:
I send the user to an external website
user makes a payment
external website redirects and posts data back to my callback URL.
So now I have the user on a mysite.com/payment-complete route but also want to display the data that was sent back.
I have an app.post endpoint to successfully grab the data:
app.post("/payment-complete", async (req, res) => {
const transactionID = req.body.trans_id;
});
How would I pass the data to the user who is already on that route? Or pass the data before the page is rendered?
The flow of data is third party > my server > user and I'm not sure how to make this work.
I'd be grateful for any help/direction with this.
If anyone comes across this - the problem was that in Express (and other languages) you can't redirect or render a view for an AJAX POST request but you can if the POST request is coming from a submitted html form. The web service was in fact POST-ing the data and redirecting my users with a form and so I could render a view.
Following code worked using Handlebars templating engine to send the render.
router.post("/payment-ok", async (req, res) => {
const transactionID = req.body.trans_id;
return res.render("rendertest", { id: transactionID });
});
Should also possibly work with app.render to send a Next.js view instead, but I wanted to render from a separate routes file.