Coffeescript external webrequest error - web-services

I'm trying to make a request to a webservice that is in my virtual machine but do not get the results. The url is perfect. Can someone help me?
$ ->
$.get "http://192.168.180.128:9000/listTasks", (data) ->
$.each data, (i, task) ->
$("#tasks").append "<option value=#{task.id}>#{task.description}</option>"

try nesting the body of the document ready function inside the ready call
$ ->
$.get "http://192.168.180.128:9000/listTasks", (data) ->
$.each data, (i, task) ->
$("#tasks").append "<option value=#{task.id}>#{task.description}</option>"

Related

How to read cookies in Elm?

I've learned in this SO question that there currently is no simple way to turn cookie-based CSRF tokens into HTTP request headers in Elm. Thus, to write a single page application (SPA) that works nicely with a Django Rest Framework backend, I need to manually retrieve the CSRF-Token from the corresponding cookie value.
How do I retrieve a cookie value in Elm? Does Elm provide runtime support for this via some Command? Or do I need to retrieve the cookie using plain JavaScript and provide it to the ELM SPA via a port?
As of Elm 0.9, you need to use Ports to read the cookie from JavaScript and pass it back to the Elm application.
In my application, I do the following. I define a fetchCsrfToken port that I use from Elm to call a JavaScript function that reads the cookie. That function then triggers a callback to Elm via a csrfTokenReciever port. My Elm application subscribes to that event via subscriptions.
-- Ports.elm
port fetchCsrfToken : () -> Cmd msg
port csrfTokenReciever : (String -> msg) -> Sub msg
-- Main.elm
init : Flags -> Url -> Key -> ( Model, Cmd Msg )
init flags url key =
-- ...
(model, Ports.fetchCsrfToken ())
subscriptions : Model -> Sub Msg
subscriptions model =
Ports.csrfTokenReciever GotCsrfToken
// index.js
app.ports.fetchCsrfToken.subscribe(function (str) {
const value = getCookie('csrftoken')
if (value === null) {
app.ports.csrfTokenReciever.send('')
} else {
app.ports.csrfTokenReciever.send(value)
}
})
Using Elm 0.19.1
First solution:
Use of 2 ports, a subscription and some JS/TS code like #viam0Zah mentioned.
Second solution:
Pass the CSRF into your flags at init
const app = Elm.Main.init({
node: document.querySelector("main"),
flags: {
csrfToken: getCookie('csrftoken')
}
});
add csrfToken to Flags
type alias Flags =
{ ---
, csrfToken : String
}
And don't forget to add a decoder for the csrfToken:
import Json.Decode as D
flagsDecoder : D.Decoder Flags
flagsDecoder =
D.succeed Flags
|> ---
|> D.required "csrfToken" D.string
If you want to be more robust and extend type safety for both solutions - flags and ports, you should check out https://elm-ts-interop.com/, it's just amazing!

How to make synchronous url requests with swift 3

I know the question has been asked before and I agree with most answers that claim it is better to follow the way requests are made async with URLSession in Swift 3. I haver the following scenario, where async request cannot be used.
With Swift 3 and the ability to run swift on servers I have the following problem.
Server Receives a request from a client
To process the request the server has to send a url request and wait for the response to arrive.
Once response arrives, process it and reply to the client
The problem arrises in step 2, where URLSession gives us the ability to initiate an async data task only. Most (if not all) server side swift web frameworks do not support async responses. When a request arrives to the server everything has to be done in a synchronous matter and at the end send the response.
The only solution I have found so far is using DispatchSemaphore (see example at the end) and I am not sure whether that will work in a scaled environment.
Any help or thoughts would be appreciated.
extension URLSession {
func synchronousDataTaskWithURL(_ url: URL) -> (Data?, URLResponse?, Error?) {
var data: Data?
var response: URLResponse?
var error: Error?
let sem = DispatchSemaphore(value: 0)
let task = self.dataTask(with: url as URL, completionHandler: {
data = $0
response = $1
error = $2 as Error?
sem.signal()
})
task.resume()
let result = sem.wait(timeout: DispatchTime.distantFuture)
switch result {
case .success:
return (data, response, error)
case .timedOut:
let error = URLSessionError(kind: URLSessionError.ErrorKind.timeout)
return (data, response, error)
}
}
}
I only have experience with kitura web framework and this is where i faced the problem. I suppose that similar problems exist in all other swift web frameworks.
In Vapor, you can use the Droplet's client to make synchronous requests.
let res = try drop.client.get("https://httpbin.org")
print(res)
Additionally, you can use the Portal class to make asynchronous tasks synchronous.
let res = try Portal.open { portal in
asyncClient.get("https://httpbin.org") { res in
portal.close(with: res)
}
}
Your three-step problem can be solved via the use of a completion handler, i.e., a callback handler a la Node.js convention:
import Foundation
import Kitura
import HeliumLogger
import LoggerAPI
let session = URLSession(configuration: URLSessionConfiguration.default)
Log.logger = HeliumLogger()
let router = Router()
router.get("/test") { req, res, next in
let datatask = session.dataTask(with: URL(string: "http://www.example.com")!) { data, urlResponse, error in
try! res.send(data: data!).end()
}
datatask.resume()
}
Kitura.addHTTPServer(onPort: 3000, with: router)
Kitura.run()
This is a quick demo of a solution to your problem, and it is by no means following best Swift/Kitura practices. But, with the use of a completion handler, I am able to have my Kitura app make an HTTP call to fetch the resource at http://www.example.com, wait for the response, and then send the result back to my app's client.
Link to the relevant API: https://developer.apple.com/reference/foundation/urlsession/1410330-datatask

On an Ember 2.5.0, how can I transition to an error template without changing the URL?

For reasons which are not important, sometimes our backend server will fail.
For both refreshing the page and requesting support, it would be useful for our application NOT to change the URL in the browser's address bar.
I've tried the following WITHOUT success:
const handleError = reason => {
let windowLocation = window.location.href
this.replaceRoute('error', new Ember.Error(reason));
window.history.pushState(page, title, windowLocation);
};
Any suggestions which might work better?
The correct answer was:
const handleError = () => this.intermediateTransitionTo('error');

ember-simple-auth qunit test with jquery mockjax

I use ember-simple-auth within my application. For my test I use QUnit together with jquery-mockjax. But I didn't get my test, login with correct credentials, to work with a mocked response. If I didn't mock, the test below works. The mocked response looks exactly like a server response.
My question is, how should I mock the response for ember-simple-auth?
test "with correct credentials", ->
expect(2)
response =
access_token : "92d50f562503e40fe783c2ebf359e0c2b37fa80758e2e3603d7e3e82a485522a"
expires_in : 7200
token_type : "bearer"
# if I remove the following line, the test works
mock_http('/oauth/token', response, 200)
visit("login")
.fillIn('#identification', 'test#test.de')
.fillIn('#password', 'tester')
.click('.btn-success').then ->
ok(find("a:contains('Logout')").length, 'logout link not visible')
ok(not find("a:contains('Login')").length, 'login link still visible')
the following test also works with mocking:
test "with wrong credentials", ->
expect(2)
response =
error : 'some error occured'
mock_http('/oauth/token', response, 401)
visit("login")
.fillIn('#identification', 'test')
.fillIn('#password', 'wrong')
.click('.btn-success').then ->
ok(not find("a:contains('Logout')").length, 'logout link not visible')
ok(find("a:contains('Login')").length, 'login link still visible')
EDIT:
Following a jsBin, that shows the problem: http://jsbin.com/ASaSaRiX/6/edit
I'm the author of Ember.SimpleAuth.
Did you configure Ember.SimpleAuth to use '/oauth/token' as the token endpoint? Otherwise it would use '/token' as the server endpoint so your mock wouldn't have any effect.
Your indetation in the first code block does not seem to be correct. It should read like this: (notice indentation change at the mock_http line)
test "with correct credentials", ->
expect(2)
response =
access_token : "92d50f562503e40fe783c2ebf359e0c2b37fa80758e2e3603d7e3e82a485522a"
expires_in : 7200
token_type : "bearer"
# if I remove the following line, the test works
mock_http('/oauth/token', response, 200)
visit("login")
fillIn('#identification', 'test#test.de')
fillIn('#password', 'tester')
click('.btn-success').then ->
ok(find("a:contains('Logout')").length, 'logout link not visible')
ok(not find("a:contains('Login')").length, 'login link still visible')
The problem is caused by jQuery version conflicts with mockjax. With the help from marcoow I found this stackoverflow question. With jQuery < 1.10 it works. Mhh... that's not nice.
By the way a working jsBin: http://jsbin.com/ASaSaRiX/11
EDIT:
You can find more detailed information here. The problem is caused by a changed in jQuery.
#marcoow: One fix is to add dataType: 'json' to the request options of Ember.SimpleAuth. Maybe you have some time to look at the informations given in the link above.

Where should I put `header` and `data` in Http_client.Convenience.http_post?

OCamlnet 3 has Http_client.Convenience.http_post.
Its API is like this:
val http_post : string -> (string * string) list -> string
Does a "POST" request with the given URL and returns the response
body. The list contains the parameters send with the POST request.
My question is::
where should I supply the header and data body for the post request?
AFAIR you can not provide custom header in Convenience method. However, you can always use the pipeline API:
let _ =
let call = new Http_client.post
"http://localhost:8080"
[("param", "value")]
in
call#set_req_header "User-Agent" "Foozilla 1.0";
call#set_req_header "Myheader" "foo";
let pipeline = new Http_client.pipeline in
pipeline#add call;
pipeline#run ();