I am new to express and node together and seem to be stuck, with what seems to be, a simple issue. I have an API route that uses GET. Route:
app.get('/api/v1/all', getAllWords);
Then inside of the getAllWords callback function, I want to check if the request that was sent was of GET or POST. This is the code I have to check the request method:
function getAllWords(request, response) {
let reply;
if (request.method === 'GET') {
console.log('This was a GET request');
// handle GET here...
}
if (request.method === 'POST') {
console.log('This was a POST request');
reply = {
"msg": "HTTP Method not allowed"
};
response.send(reply)
}
}
When I use Postman to send off a GET request it works just fine. But when sending a POST request I get the generic express.js "Cannot POST /api/v1/all".
Why did it the response.send(reply) not work for the POST method?
app.get(...) define endpoint that only matches with GET method. If you want to handle POST method you must supply seperate middleware in app.post(...)
You can make use of app.all(...) to handle both GET and POST requests but it also accepts other kind of requests such as PUT and DELETE. I prefer separating the GETand POST request though.
Related
I've made an HttpInterceptor for the front-end that send every request with some default headers and automatically encrypt body/url for every request and a middleware for the back-end that check the headers and decrypt the packet if needed.. Now I have a problem with the response middleware, because I want to send the response with encrypted body only for some requests.
app.use((req,res,next)=>{
if(req.headers['x-data-encoded'] && (req.headers['x-server'] == "HP")){
res.append('X-Encoded-Data', true);
var nsp = res.send;
res.send = function(data){
var body = Crypto.encodeData(data); // Result a string of letters and numbers
nsp.apply(this, body);
}
}
next();
});
Caught exception: TypeError: CreateListFromArrayLike called on non-object
I think that error appears because send method waits an object and it is receiving a String. If you assign manually body an object this error should dissapear or change to another one.
Besides, second parameter of apply should be an array.
Hope it helps
Here in the GET /facebook route i receive the authorization code from front-end after receiving that, i have to make a POST request to /facebook/signin
How can I redirect GET /facebook to POST /facebook/signin
router.get('/facebook', (req, res) => {
// res.send(req.query.code);
res.redirect('/facebook/sign'); // = GET /facebook/sign
});
POST route
router.post('/facebook/sign', (req, res, next) => {
console.log(req.query.code);
// i will do mine stuff....
});
You can also write 1 handler method and use it in both routes;
function doFacebookSignIn(req, res) {
// Your code here.
}
or
// Must be defined before using it in code.
var doFacebookSignIn = function(req, res) {
// Your code here.
};
router.get('/facebook', doFacebookSignIn);
router.post('/facebook/sign', doFacebookSignIn);
But as I pointed out in the comments, you should be aware that when using a request body in a GET request, there are some things to consider.
You cannot redirect GET to POST, a redirect is used to notify an HTTP client that a resource has changed location and should attempt the same request using the new location.
It is noted in the RFC that in some cases POST will be downgraded to GET when the request is re-issued.
Note: When automatically redirecting a POST request after
receiving a 301 status code, some existing HTTP/1.0 user agents
will erroneously change it into a GET request.
If a POST request is expected on the server, then the client should send a POST request rather than a GET request.
I'm currently trying to use an API and for the API, the developer console of that app asks the developer to submit a callback URL. Whenever the user of the app does something, it submits a GET request to the callback URL and I can retrieve data from that request. The current url I am using is https://appId:javascript-key=myJavascriptKey#api.parse.com/1/functions/receiveInfo. How can I handle the data, a.k.a the GET parameters, from the GET request? I found an answer on Parse.com that says how to retrieve data from a POST request, but all it says is that data = request.body. Do I do the same for GET requests and if so what do I do after that? Is request.body a json value?
Parse.Cloud.define("receiveInfo", function(request,response){
var params = request.body;//is this right to get the GET parameters they send? if so what do I do next?
});
The documentation has your solution at: https://parse.com/docs/cloud_code_guide#functions
For GET requests you have to use the request.params object which has all your request parameters for a GET are there. POSTS are sent in the request body, GET in the request parameters.
It looks like you are trying to get the params you can use something similar to:
Parse.Cloud.define("myMethod", function(request, response) {
if(request.params.myparam == "moo") {
response.success("Cow!");
}
else {
response.error("Unknown type of animal");
}
});
I have an issue where I'm trying to make a post request using Restangular:
I'll setup the query like so:
var auth = Restangular.all('auth');
var check = auth.one('check');
Then I'll do the post request like so:
var user = {
email: 'randomemail#gmail.com',
pass: 'randompass'
}
check.post(user)
However, the request shows an error, when I check the network, the request is sent as so :
http://localhost/auth/check/[object object]
Why does the post request attach the object like a query parameter instead of sending it in the request body?
If i'm formatting this post request incorrectly, can someone point out the correct way to format a post request using one and all in Restangular.
Thanks!
When you post to a one(), post() is actually expecting a subElement as the first argument, which is why it's attaching the object passed to the path...
(from documentation)
post(subElement, elementToPost, [queryParams, headers]): Does a POST
and creates a subElement. Subelement is mandatory and is the nested
resource. Element to post is the object to post to the server
To post to /auth/check, you can use customPOST()...
auth.customPOST(user, 'check');
Edit - Here are a couple of examples if you are set on using post()...
Restangular.one('auth').post('check', user);
Or
auth.all('check').post(user);
I have a route which accepts DELETE requests, and I know that with Express you can add
<input type="hidden" name="_method" value="delete" />
to a form that sends a POST request to the url.
However, how would you do this with a link instead of a form?
This is not supported for GET requests:
methodOverride() only checks req.body (POST arguments) and request headers - neither can be set for a regular link (you can however set custom headers in AJAX requests even if they use GET).
This make senses since otherwise it could be a major issue even when using CSRF tokens. You can never know when a browser will decide to prefetch a link - so GET requests should never perform actions such as deleting things.
If you really need it and do not care about the drawbacks, consider writing a custom function:
function methodOverrideGET(key) {
key = key || "_method";
return function methodOverrideGET(req, res, next) {
if (req.originalMethod != req.method) {
// already overridden => do not override again
next();
return;
}
req.originalMethod = req.method;
if (req.query && key in req.query) {
req.method = req.query[key].toUpperCase();
delete req.query[key];
}
next();
};
};
Now you can .use(methodOverrideGET) after .use(methodOverride) and then simply add _method=DELETE to the query string.