I can't call PATCH method using Pug, Mongoose and Express.js - mongodb

I am new to code and I apologize in advance for all my noob mistakes.
I'm trying to set a new color to an existing object stored in MongoDB using the PATCH method in the browser, but I don't understand why its not working while the GET and POST methods are working.
I have to mention that the PATCH method works in Postman.
The code in my pug file:
form(action=`/posts/changeColor` + id, method="patch")
label Enter variable color:
input(type="text", name="color")
button(type="Submit") Submit
And the code in express:
router.patch('/posts/changeColor/:id', async(req, res)=>{
try{
const test = await products.updateOne({_id: req.params.id},{$set:{productColor: req.body.color}});
res.json(test);
}catch(err){
console.log(err);
}
}
This is the error I get after pressing the "Submit" button
Cannot GET posts/changeColor/62723c3ed31baa41d5e9b0e1

HTML forms can not initiate PATCH HTTP requests.
See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#attr-method

Related

'then is not a function' in MongoDB Stitch Webhook

The MongoDB Stitch Webhook docs describe my precise use case: using a POST method to call insertOne then return the inserted _id.
I pasted the example below (directly from the docs) into the Stitch Function Editor.
exports = function(payload, response) {
const mongodb = context.services.get("mongodb-atlas");
const requestLogs = mongodb.db("test").collection("requestlogs");
requestLogs.insertOne({
body: EJSON.parse(payload.body.text()),
query: payload.query
}).then(result => {
response.setStatusCode(201);
response.setBody(result.insertedId);
})
};
I executed the function in the Function Editor console by calling:
exports({query: {arg1: 'hello', arg2: "world!"}, body:BSON.Binary.fromText('{"msg": "world"}')})
An error is returned indicating that .then is not a function.
error: TypeError: 'then' is not a function
Are the docs wrong, or I have I gone astray?
Certain methods, like .then, throw errors in the function editor. In my case, this was a shortcoming of the function editor, rather than an error in my code. Calling the webhook with fetch or Postman, the function executed as expected.
The Incoming Webhook docs contain a special note:
If you want to debug a webhook function response from the function
editor, you must manually provide the HTTP response object when you
run the function.
exports( { body: "This document is the webhook payload" }, new
HTTPResponse() )
That alerted me to the idiosyncratic nature of the function editor as a JS handler. Using Postman I confirmed the function ran without errors when called. The error generated by the function editor was a red herring.

Why when I upload of file-list the server-side code get an empty list?

First of all here's my jsFiddle, so you can see what I'm talking abuout.
I'm using blueimp/jQuery-File-Upload to manage files in the GUI of my asp-net application (server-side code is OK). If I manage the upload one-by-one I am able to upload that file successfully but as I try to submit the whole list the server does not recognize data and get only an empty list.
Here's the piece of code where my issue is:
//initialize fileupload()
$('#fileupload').fileupload({
//I call this function when I add file(s) to the list
add: function (e, data) {
//I do some more actions here
//Then I define this function when the submit button is clicked
$('#submitButton').click(function () {
//fix this?
data.submit();
});
}
)};
So, what am I doing wrong?
Your server should support multipart forms!
A solid handler for ASP.NET is Backload

Ember js RESTAdapter PUT request adds .json to the end

I've been trying to learn Ember and I have a question.
In my store I'am getting data from .json like below. I have tried without buildUrl function but cant load the json file, then found this solution on SO.
CocktailApp.Store = DS.Store.extend({
revision: 12,
adapter: DS.RESTAdapter.extend({
bulkCommit: false,
url: "http://localhost:8888",
buildURL: function(record, suffix) {
var s = this._super(record, suffix);
return s + ".json";
}
})
});
Now comes my question: When I commit the chances (by pressing add to favs or remove from favs) RESTAdapter adds ".json" at the end of to PUT request. See the below code and screenshot
CocktailApp.CocktailController = Ember.ObjectController.extend({
addToFav: function () {
this.set('fav',true);
this.get('store').commit();
},
removeFromFav: function () {
this.set('fav',false);
this.get('store').commit();
}
});
I think thats why my PUT request can not be handled. But If I remove the builtURL function no json loaded at all. How can I resolve this problem?
Thanks
If the API endpoint url does not require .json at the end of it, then remove that line from your buildURL function. My guess is that the example code you got was consuming a ruby on rails api, or something similar.
remember, when you send a GET, PUT, POST, or DELETE to a url, that url needs to actually be a real endpoint. You can't just add extraneous stuff to it and have it still work.

Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?

I've implemented a REST/CRUD backend by following this article as an example: http://coenraets.org/blog/2012/10/creating-a-rest-api-using-node-js-express-and-mongodb/ . I have MongoDB running locally, I'm not using MongoLabs.
I've followed the Google tutorial that uses ngResource and a Factory pattern and I have query (GET all items), get an item (GET), create an item (POST), and delete an item (DELETE) working. I'm having difficulty implementing PUT the way the backend API wants it -- a PUT to a URL that includes the id (.../foo/) and also includes the updated data.
I have this bit of code to define my services:
angular.module('realmenServices', ['ngResource']).
factory('RealMen', function($resource){
return $resource('http://localhost\\:3000/realmen/:entryId', {}, {
query: {method:'GET', params:{entryId:''}, isArray:true},
post: {method:'POST'},
update: {method:'PUT'},
remove: {method:'DELETE'}
});
I call the method from this controller code:
$scope.change = function() {
RealMen.update({entryId: $scope.entryId}, function() {
$location.path('/');
});
}
but when I call the update function, the URL does not include the ID value: it's only "/realmen", not "/realmen/ID".
I've tried various solutions involving adding a "RealMen.prototype.update", but still cannot get the entryId to show up on the URL. (It also looks like I'll have to build the JSON holding just the DB field values myself -- the POST operation does it for me automatically when creating a new entry, but there doesn't seem to be a data structure that only contains the field values when I'm viewing/editing a single entry).
Is there an example client app that uses all four verbs in the expected RESTful way?
I've also seen references to Restangular and another solution that overrides $save so that it can issue either a POST or PUT (http://kirkbushell.me/angular-js-using-ng-resource-in-a-more-restful-manner/). This technology seems to be changing so rapidly that there doesn't seem to be a good reference solution that folks can use as an example.
I'm the creator of Restangular.
You can take a look at this CRUD example to see how you can PUT/POST/GET elements without all that URL configuration and $resource configuration that you need to do. Besides it, you can then use nested resources without any configuration :).
Check out this plunkr example:
http://plnkr.co/edit/d6yDka?p=preview
You could also see the README and check the documentation here https://github.com/mgonto/restangular
If you need some feature that's not there, just create an issue. I usually add features asked within a week, as I also use this library for all my AngularJS projects :)
Hope it helps!
Because your update uses PUT method, {entryId: $scope.entryId} is considered as data, to tell angular generate from the PUT data, you need to add params: {entryId: '#entryId'} when you define your update, which means
return $resource('http://localhost\\:3000/realmen/:entryId', {}, {
query: {method:'GET', params:{entryId:''}, isArray:true},
post: {method:'POST'},
update: {method:'PUT', params: {entryId: '#entryId'}},
remove: {method:'DELETE'}
});
Fix: Was missing a closing curly brace on the update line.
You can implement this way
$resource('http://localhost\\:3000/realmen/:entryId', {entryId: '#entryId'}, {
UPDATE: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId' },
ACTION: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId/action' }
})
RealMen.query() //GET /realmen/
RealMen.save({entryId: 1},{post data}) // POST /realmen/1
RealMen.delete({entryId: 1}) //DELETE /realmen/1
//any optional method
RealMen.UPDATE({entryId:1}, {post data}) // PUT /realmen/1
//query string
RealMen.query({name:'john'}) //GET /realmen?name=john
Documentation:
https://docs.angularjs.org/api/ngResource/service/$resource
Hope it helps

node.js: expressjs with mongoose

I'm working on my first node.js / express / mongoose app and I'm facing a problem due to asynchronisation mechanism of node.js. It seems I do not do the thing correctly...
Here is the test route I defined using express:
app.get('/test', function(req, res){
var mod = mongoose.model('MyModel');
mod.find({},function(err, records){
records.forEach(function(record){
console.log('Record found:' + record.id);
// res.send('Thing retrieved:' + record.id);
});
});
});
When I issue a http://localhost/test, I'd like to get the list of records of type 'MyModel' in the response.
The code above is working fine but when it comes to returning this whole list to the client... it does not work (the commented res.send line) and only returned the first record.
I'm very new to node.js so I do not know if it's the good solution to embed several callback functions within the first callback function of app.get . How could I have the whole list returned ?
Any idea ?
What you should be doing is:
mod.find({},function(err, records){
res.writeHead(200, {'Content-Length': body.length});
records.forEach(function(record){
res.write('Thing retrieved:' + record.id);
});
});
Please always check the documentation as well:
http://nodejs.org/docs/v0.3.8/api/http.html#response.write
I missed that you was using express, the send function is part of express and extend's the serverResponse object of node (my bad).
but my answer still applies, express's send function sends the data using ServerResponse.end() so there for the socket get's closed and you cannot send data any more, using the write function uses the native function.
You may also want to call res.end() when the request is fully completed as some item's within express may be affected