Using Koa, how do I get post variables - koa

Let's say I want o get a simple variable posted to a Koa app without using an extension, how would I do it?

You have to use the official koa-bodyparser module.
Then all the POST parameters will be available in this.request.body.
From the docs:
app.use(function *() {
// the parsed body will store in this.request.body
// if nothing was parsed, body will be an empty object {}
this.body = this.request.body;
});

Related

Retrieve url param value from strapi

How do I get the parameters value passed in the url? For example, my url is /forgot-password?email=testing#example.com&token=fb49d692186dd4744af50446fad2f031
I want to get the value of email and token. All I found from the doc is only about the segment as parameters value which set from route as /user/:id which is different usage for my case.
Strapi uses koa.
Therefor you can just use ctx.request.query.
Inside your handler:
async test(ctx) {
let queryObj = ctx.request.query
//use them...
}
For your stated request the object will contain:
{
email: 'testing#example.com',
token: 'fb49d692186dd4744af50446fad2f031'
}

Using the result of an AJAX call as an AMD module [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I'm using RequireJS while prototyping an application. I'm "faking" a real database by loading a json file via ajax.
I have several modules that need this json file, which I noticed results in multiple http requests. Since I'm already using RequireJS, I thought to myself "hey, why not load this json file as another module". Since a module can return an object, it seemed reasonable.
So I tried this:
// data.js
define(function(require){
const $ = require('jquery')
var data = {}
$.getJSON('/path/to/data.json', function(json_data){
data = json_data
})
// this does not work because getJSON is async
return data
})
// some_module.js
define(function(require){
const my_data = require('data')
console.log(data) // undefined, but want it to be an object
})
I understand why what I'm doing is not working. I'm not sure what the best way to actually do this would be though.
Things I don't want to do:
Change getJSON to async: false
add a while (data == null) {} before trying to return data
Is there an AMD-y want to accomplish what I'm trying to do? I'm sure there's a better approach here.
Edit
I just tried this. It works, but I'm not sure if this is a good or terrible idea:
// in data.js
return $.getJSON('/path/to/data.json')
// in some_module.js
const my_data = require('data')
my_data.then(function(){
console.log(my_data.responseText)
// do stuff with my_data.responseText
})
My concern is (1) browser support (this is a "promise", right?) and (2) if multiple modules do this at the same time, will it explode.
Because this question is specifically referring to using JQuery, you can actually do this without a native promise using JQuery's deferred.then().
// in data.js
return $.getJSON('/path/to/data.json')
// in some_module.js
const my_data = require('data') // this is a JQuery object
// using JQuery's .then(), not a promise
my_data.then(function(){
console.log(my_data.responseText)
// do stuff with my_data.responseText
})
Based on the description of then() in JQuery's docs, it looks like this is using a promise behind the scenes:
As of jQuery 1.8, the deferred.then() method returns a new promise that can filter the status and values of a deferred through a function, replacing the now-deprecated deferred.pipe() method. [...]
Callbacks are executed in the order they were added. Since deferred.then returns a Promise, other methods of the Promise object can be chained to this one, including additional .then() methods.
Since JQuery's .then() does work in IE, I guess they are polyfilling the promise for IE behind the scenes.

Net Web API - How to pass a URL as input parameter on a Get

I am trying to pass a URL as a input parameter to a ApiController from an Angular REST call. The URL comes as a query string (this is a Provider Hosted app in SharePoint, I need the URL to query SP FWIW).
Here is the method signature in the ApiController:
// GET: api/ProjectSite/5
public IEnumerable<ProjectSite> Get(string id)
{
return ProjectSite.GetAllProjectSites(id);
}
And here is where I am making the call in Angular:
var spUrl = "'" + getParameterByName("SPHostUrl") + "'";
var queryUrl = "/api/ProjectSite/" + encodeURIComponent(spUrl);
return $http.get(queryUrl);
This generates a GET request that looks like this:
https://localhost:12345/api/ProjectSite/https%3A%2F%2Fcompany.sharepoint.com%2Fsites%2Fsite_dev%2Fweb
When I do I get 'HTTP 400 (Bad Request)' back. If I stop on a break point in the Angular code and change the input param to a simple string (e.g. 'asdf') the REST call is made and I see the Api is called. If I do not change the string and put a breakpoint inside the Get Api method the breakpoint is not reached, indicating that the code is blowing up somewhere in the route engine.
What I don't get is, while its encoded, the string I am trying to pass in should still be treated as a string, right? I also tried changing the input to Uri but that doesn't appear to work (and Uri isn't listed as a supported input type, anyways).
Anyone know how to pass a URL as input parameter?
Have you tried calling it using a query string?
var queryUrl = "/api/ProjectSite?id=" + encodeURIComponent(spUrl);

Web API - JObject from URI

Web API allows me to capture the body of a POST request in a JObject:
$.post('/api/Query/DoSomething', { Foo: "one", Bar: 4 });
public string Post(JObject data)
{
// data is populated
}
However the same technique does not work with a get request and URI parameters.
$.get('/api/Controller', { Foo : "one", Bar : 4 });
public string Get([FromUri]JObject data)
{
// data is empty
}
Any workaround here?
It doesn't work because a GET request does not have a body, and hence no content type. Therefore, Web API does not know that you have JSON in your URL. You have a few choices:
Pass your data as query string parameters, as is traditionally done in GET requests, and change your method to accept those parameters individually, or in a regular class (POCO).
Change your GET method to accept a string instead of a JObject, then use JSON.Net to deserialize it manually, e.g. JObject obj = JObject.Parse(data);
If you're feeling ambitious, you might be able to implement a custom binder to do this.
My recommendation is option 1. Traditionally, a GET method is just intended to look something up, so you really should only be passing IDs and simple query options anyway. It is unusual to be passing JSON data in a URL. Also the length of URLs can be limited by some browsers. If you find you are needing to pass JSON data, use POST (or PUT) instead.
You can create an object and bind to it using the FromUri.
Check out this solution which I am using https://stackoverflow.com/a/49632564/2463156.

dojo.io.script.get vs dojo.xhrGet

I have spent days working on this and really feel dumb. I have been working on demos and samples that never work when I try it locally with my own url. I have a web service that returns results back in json and am just basically trying to call it using dojo and for now just view the results. I took the search google example and just substituted the url and parameters. Now perhaps I still do not understand the basics so:
- io.script.get vs xhrGet
if using cross domain urls it is better to use io.script.get? correct?
now what is the callbackparam? is this the function that is being called in the webservice?
My webservice url is as follows:
http://xxx.xxx.x.xxx/WcfServices/WcfInstance/Service1.svc/RetrievData?query=Word
when I use the following code I get nothing displayed.
function searchGoogle() {
// Look up the node we'll stick the text under.
var targetNode = dojo.byId("rules");
// The parameters to pass to xhrGet, the url, how to handle it, and the callbacks.
var jsonpArgs = {
url: "http://xxx.xxx.x.xxx/WcfServices/WcfInstance/Service1.svc/RetrieveData?",
callbackParamName: "callback",
content: {
query:"dojowords"
},
load: function (data) {
// Set the data from the search into the viewbox in nicely formatted JSON
targetNode.innerHTML = "<pre>" + dojo.toJson(data, true) + "</pre>";
},
error: function (error) {
targetNode.innerHTML = "An unexpected error occurred: " + error;
}
};
dojo.io.script.get(jsonpArgs);
}
dojo.ready(searchGoogle);
Here is what the webservice results look like:
"{\"rules\":[{\"value\":\"AllState\"},
{\"value\":\"Cidade de Goa beach\"},{\"value\":\"Euro 2012\"},
{\"value\":\"Euro2012\"},{\"value\":\"European&Championship\"},
{\"value\":\"Holiday Inn Resort\"},
{\"value\":\"Holiday Inn Resort goa\"},
{\"value\":\"Hotel Goa\"},{\"value\":\"Hyatt Goa\"},{\"value\":\"I buy car\"},...
If I get this part correct then at least I know I have data which I can then bind to a datagrid or chart.
dojo.io.script.get is for all cross domain requests.
xhrGet is for same domain requests.
dojo.io.script.get uses a hack which expects jsonp or json padding as a result. This wraps the response of the web service call inside a self executing function. The function name is the callback name. This has to be wired before the call so it knows what already defined function to call when a response comes back.
All of the arguments are well documented http://dojotoolkit.org/reference-guide/1.7/dojo/io/script.html
My guess as to why your service isn't working is because you wrote the web service and it does not handle jsonp. It is not wrapping its response inside the callbackparamname.
your results should look something like
callback({json});
where callback is whatever you set up in callbackParamName
you can also remove the ? from your url, that should be handled for you.

Resources