Delete multiple array // "route doesn't exist" - node.js

I tried to delete the array of multiple elements but I guess I do something wrong.
My app looks like this picture
So, when I press on mass delete I get an error that the route doesn't exist (picture)
I think it's because in my node route look like
import express from "express";
const router = express.Router();
import {
createProduct,
getAllProducts,
deleteProduct,
} from "../controllers/productController.js";
router.route("/createProduct").post(createProduct);
router.route("/").get(getAllProducts);
router.route("/:id").delete(deleteProduct);
export default router;
I tried in postman and it's successful, I think because I pass by id, but now in my state I have selected items array and its a bunch of ids picture
So, how in route write that it's an array?
Thanks in advance

The error is because the only delete endpoint that exists is the one where you pass an id as the parameter router.route("/:id").delete(deleteProduct);, so when you target localhost:5000/api/v1/ with a HTTP DELETE it throws a 404 error.
For multiple deletion you can maybe create a new route say:
router.route("/deleteMassProducts").delete(deleteMassProducts);
you can then send the array of selected items in the request body and then delete them with whatever logic you prefer. You can also accomplish this without changing anything on the backend, just loop through the selected items and target the delete route with the :id parameter multiple times for each of the selected items id.

Related

Why node app crashes when req.files is null?

I have a frontend app(react) where the user can edit the product like price, description, delete images and add images.
The problem occurs when the user does not want to add new images.
Then on the backend(nodejs) req.files.newImages as I named it is null
and the backend crashes.
When I add one image or more everything works as it should because req.files.newImages has a value.
How to cover the case when the user does not want to add new images and prevent the app from crashing
I use express-fileupload and I use axios and put method to send data.
routes.put("/edit-product", (req, res) => {
console.log(req.files.newImages) // - result app crashed
}
Error in console: TypeError: Cannot read property 'newImages' of null;
You can simply check if there are any files like this:
if (req.files) {
// do something
}
Alternatively you can use optional chaining:
console.log(req.files?.newImages); // will log "undefined"
first check if it comes with console.log(req.files) with another name, if not, make sure you send it as "multipart" on the front-end side

passing data from parent to child angular 4

I have some general questions, I start of on page main.ts
Via onInit I am grabbing data from a mongoose database server, which I save in an array.
This array needs to be available in other components. The way I do this right now, which seems to work, by using a service.ts
In the service I have a lot BehaviorSubjects and Subjects. So whenever I get the array data from mongoose I send a message to the service, and the other components subscribe to that message.
I am sometimes using Subject instead of BehaviorSubject because it throws error messages as in HTML I am using *ngFor and it expects an array, not a string 'default message'.
I am just wondering if this is a correct setup to move data between pages.
Right now I am also using this message system for updates on my component.
So if someone makes a comment or post on my website I send a message to my service which in turn updates an observable and my component subscribes again to that.
Are there better ways to update my site for new data and is there an easy way to explain why sometimes I get this error message from *ngFor and in other cases it doesn't throw this error whilst still using *ngFor.
i.e. when I update an observable will the component receive the message straight away or will it receive onInit.
With that also the question if it is best practice to use the below in the constructor of the component or the onInit.
I unsubscribe OnDestroy.
this.newService.currentMessageComment
.takeWhile(() => this.alive)
.subscribe(message => {
service.ts
public messageSourceMarketCap = new BehaviorSubject<any>('default message');
currentMessageMarketCap = this.messageSourceMarketCap.asObservable();
public messageSourceHistory = new Subject<any>();
currentMessageHistory = this.messageSourceHistory.asObservable();
public messageSouceApi = new BehaviorSubject<any>('default message');
currentMessageApi = this.messageSouceApi.asObservable();
public messageSourceBody = new BehaviorSubject<any>('default message');
currentMessageBody = this.messageSourceBody.asObservable();
Why are you using BehaviouSubject. I think in your case Subject will be better. BehaviouSubject fits in case when you want to pass a initial value while creating observable.
You can also quick fix by emiting an empty array as ngFor expects an array. Change from "default message" to [].
Hope it will help

REST method GET for searching by criteria as json fro mongodb

I have an nodejs server with express and mongoose and I'd like to use method GET for search accoring to criteria which I'd like to provide as JSON object does anyone can help me how to implement it?
Or maybe should I use POST or PUT to make it?
http://hostname/modelname?criteria1=1&criteria2=2
router.route('/modelname')
.get(function (req, res, next) {
req.query.criteria1 === 1 // true
req.query.criteria2 === 2 // true
});
If you are unsure of what HTTP VERB you'd want to use,
POST - is primarily used for creating resources on the server
PUT - is used to update an existing resource
GET- to retrieve a resource
I would use GET in this case
GET http://myhost.com?q=word1+word2+word3+word4
app.get('*', function(req, res) {
// do something with the req.query.q array
});
You've got two options - using HTTP GET params or encoding whole criteria as JSON string and passing that string.
First option, by using params:
?crit[foo.bar][$eq]=abc&crit[foo.baz][$ne]=def
You can read it in nodejs/express via req.query.crit. But this is bad idea because there's no way of retaining data types. For example number 1 becomes string "1". Don't use it - MongoDB is data type sensitive so query {"foo.bar":{$eq:1}} is completely different from {"foo.bar":{$eq:"1"}}
Second option is to urlencode JSON criteria:
?critJSON=%7B%22foo.bar%22%3A%7B%22%24eq%22%3A%20%22abc%22%7D%2C%22foo.baz%22%3A%7B%22%24ne%22%3A%20%22def%22%7D%7D
And parse it on nodejs/express side:
var crit = JSON.parse(req.query.critJSON)
This way your data types are retained and it will work as expected.

Is it ok to work directly on the data in req.body?

I'm working on an app in Node/Express/Jade.
I have a GET route which render a form. When the user submit this, a POST route is handling the request. I use bodyParser, which populate the req.body.
I then sanitize, validate and generate new data directly in the req.body:
// Shorthand variable
var doc = req.body;
// Sanitise and transform user input
doc.company = sanitize( doc.company ).trim();
doc.contact_person = sanitize( doc.contact_person ).trim();
...
// Validate user input
validator.check( doc.company, 'Some error message' ).notEmpty();
validator.check( doc.contact_person, 'Another error message' ).notEmpty();
...
// Generate new object data
doc.slug = sanitize( doc.company ).toSlug();
...
Question: is if there are any special reason for me not to edit the data directly in the req.body? Should I instead making a new "doc" object from the data in req.body, and in that new object sanitize, validate and add the new generated data.
It's fine to edit data in req.body. The only thing you should be aware of is that the next route or middleware will get a modified version of req.body.
So, you may create a single route/middleware to sanitize and transform your req.body and then use transformed results in multiple routes.
You can definitely modify it. For example, the express.json middleware parses raw body data into JSON for the rest of the middleware chain.
It's best to use a copy if your intention isn't to alter data for the rest of the chain, even if it won't interfere with correct operation. It prevents sometimes hard-to-debug errors that might crop up in later development.

how to get URI as parameters in NodeJS

How can i get the URI and use it as params in nodejs. I am using express.
http://localhost:3000/getParams/param1/param2/param3/paramN
I want to get "/param1/param2/param3/paramN".
This is my current code:
app.get("/getParams/:params", test.params);
Thanks!
You can access the full path as one param, or you can access each segment as a separate param. To get as one param:
app.get('/mysvc/:input(*)', function(req, res)
{
console.log(req.params.input);
// ...
});
Notice the route which says everything (regex match of *) after /mysvc/ will be mapped to the input reques param. Then you can reference it via req.params
In this example, a request to /mysvc/foo/bar will output foo/bar
If you want to get each segment as a separate param then:
app.get('/mysvc/:param1/:param2'
access via req.params.param1, req.params.param2, etc...
In express parameters are available in the req object req.params.parameterName so in your case you can access it within the route like this req.params.params.
The params that you can access from the handler depends upon the route definitions. If you route is like
/my/:one/:two/:three
then you can access them as
req.params.one
req.params.two
req.params.three

Resources