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");
}
});
Related
I am trying to send a JSON response, and redirect the page at the same time. It is not happening. Is there any way to redirect in Express.js while sending some JSON response to client? I want to use this JSON response to render the value to the redirected HTML page.
My Code -
//I tried using the below code. But it is not working
const app = express();
app.get('/user', authenticationMiddleware, (req,res) => {
res.send({name : "StackOverFlow", reason : "Need help!"});
res.redirect('/user/me');
})
Expected result :
I should get the {name : "StackOverFlow", reason : "Need help!"} as response (I will use fetch() to get the response) in the redirected client side HTML.
What you'll want to do is setup your response object to look something like the below:
res.send({name : "StackOverFlow", reason : "Need help!", redirect_path: "/user/me"});
And then in the function callback on your client (where you're making the fetch request), you'll want to pickup the value of response.redirect_path and pass it into a JS redirect method.
You could use something like:
location.href = response.redirect_path
Example usage (on the client-side)
fetch("http://yousite.com/endPoint")
.then((resp) => resp.json()) // Transform the data into json
.then(function(response) {
if (response.redirect_path) { //optional check to see if a redirect path exists
location.href = redirect_path;
}
})
})
Bear in mind, I'm assuming that the argument passed in your fetch response callback function is called 'response', if it is 'res' or something else, you'll have to adjust the code above accordingly.
You should send json response to client side and under success function of your ajax call use window.open(redirecturl)
Let me know if it didn't help
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.
There's a webapp that makes a request (let's call it /api/item). This request returns a json body with a field called itemData which is normally hidden from the user, but I want to make that shown.
So how do I make a userscript that listens for the request at /api/item and displays the itemData field?
For reference the way the webapp is making the request is:
return Promise.resolve(new Request(e,r)).then(sendCookies).then(addLangParam).then(addCacheParam).then(addXsrfKey).then(checkZeroRating).then(function(e) {
return fetch(e)
}).then(checkStatus).then(checkApiVersionMismatch).then(checkApiResponse)
Most of that is irrelevant, but the important part is Request (I think).
This webapp is not using XMLHttpRequest, but the Fetch API.
You can use the fetch-intercept npm module to intercept fetch requests. Example code:
import fetchIntercept from 'fetch-intercept'
fetchIntercept.register({
response(response) {
console.log(response)
return response
}
})
Do you have access to the promise returned ?
If so, then you may add another "then".
Otherwise, you may overwrite "checkApiResponse"
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 am facing very strange issue here. I have a servlet running on my machine which renders my web page based on some input parameters.
Now, my screen capture with PhantomJS is not working if I try to send my data as a JSON object as a POST request type. For e.g. if I try:
Client side
var data = {"op": "get"};
page.open(address, 'POST', data, function (status) {
if (status !== 'success') {
console.log('[ERROR] :: Unable to fetch the address - ' + address + ", with data - " + data);
phantom.exit();
} else {
page.render(output);
}
console.log('processing...');
});
Server side
Now, on the server side, I am using Apache Velocity View templating so I have a single method which handles both get and post like :
public Template handleRequest(HttpServletRequest request, HttpServletResponse response,
Context context){
System.out.println(request.getParameter("op"));
//Always null
}
However, if I try sending my data from phantomjs as:
var data = "op=get&..."
It works
Also, at many places elsewhere in my code..I am doing Ajax POST requests to the same servlet and it works perfectly for all those request.
Would anybody explain why my servlet is not reading the JSON parameters passed from Phantomjs?
Servlets deal with simple request, so they only know how to parse (natively) HTTP parameters, either GET parameters from the URL, or POST parameters sent as application/x-www-form-urlencoded. Newer versions of the Servlet specification can also read multipart/form-data.
But there's nothing about JSON mentioned either in the Servlet or the HTTP specifications. So you must use a library that knows how to parse JSON and make the resulting object available in the Velocity context.