Angular2/http (POST) - angular2-http

I'm a new guy on Angular 2, i get stuck on Angular Http post. I put all code HERE`
addHero(name: string): Observable<Hero>{
let body= JSON.stringify({name});
let headers = new Headers();
headers.append('Accept','application/json');
headers.append('Content-Type','application/json');
let options = new RequestOptions({ headers: headers });
console.log(body);
return this.http.post(this.heroesUrl, body, options).map(this.extractData).catch(this.handleError)
//return new Observable(name=>{id:3; name:name})
}
`
When i click on Add Hero button, it throw a bug as image below
enter image description here
Anyone know what wrong with this. Thank in advance

To post data you need to create an API or simulate one. According to the docs you can only use get from a .json file.
For learning angular 2 http I would suggest setting up an in memory api as in the tutorial. See the InMemoryDataService here: https://angular.io/docs/ts/latest/tutorial/toh-pt6.html
And more about how it works here: https://angular.io/docs/ts/latest/guide/server-communication.html#!#in-mem-web-api
And the working plunker from the tutorial: https://angular.io/resources/live-examples/toh-6/ts/plnkr.html

Related

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

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

SoapUI 5.7.0 mockRequest.requestContent is empty for POST request

I am using SOAP UI 5.7.0 to mock a REST service and it is working fine. Only, when I want to access the body of a POST request with mockRequest.requestContent, the correct content is returned only in the first call, but from then on, it always returns the empty string.
I tried the call in OnRequestScript and in the POST requests own Dispatch script but the behavior is the same in both cases. I have the suspicion, that the Stream of the request is already read somewhere else and so does not return any more content. But I don't know what to do about it.
I wonder what is the correct way to read the content of a POST request.
Thank you
Appears to be a known issue, see posts in the community forum here and here.
this seems to be an old bug of PUT operation in REST mocks.
Unfortunately, this is a bug. There is an internal defect of SOAP-2344 for this issue. This applies for the PUT and DELETE methods for a REST mock service.
I have the same issue with a PATCH request.
Use the following trick to get the body of the PUT and DELETE requests:
mockRequest.with {
if (method.toString() == 'PUT' || method.toString() == 'DELETE') {
InputStreamReader isr = new InputStreamReader(request.getInputStream(), "UTF-8")
BufferedReader br = new BufferedReader(isr)
StringBuilder sb = new StringBuilder()
while ((s=br.readLine())!=null) {
sb.append(s)
}
def requestBody = new groovy.json.JsonSlurper().parseText(sb.toString())
log.info "requestBody: " + requestBody
}
}
I use it on the project but I don't really remember how where I got the snippet from. I had to change some parts to make it work as far as I remember. Give it a try.

How to post grade on an assignment using canvas LMS API and UnityWeb Request or similar?

I am working on a gamification project whose goal is to build a WebGL game with Unity and post the final score as a grade on an assignment using the canvas LMS API. I need to know two things: how to authenticate using a bearer token for now (I know how to create the token already and I will need to use auth 2.0 later) and how to post a grade on an assignment using UnityWeb Request or similar. I have tried using restsharp, the vs code recognized it, but Unity did not. Also tried making a connection with node.js, Unity and node.js connected successfully, but the node wrappers I was using did not work.
In the worst cenario I would like to be able to post a comment on the assignment (I would pass the final grade as a string).
This is what I've tried with httpWebRequest:
string api_token = "bearer token here";
//initializing HttpWebRequest object
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("domain here");
IWebProxy theProxy = request.Proxy;
if (theProxy != null)
{
theProxy.Credentials = CredentialCache.DefaultCredentials;
}
CookieContainer cookies = new CookieContainer();
request.UseDefaultCredentials = true;
request.CookieContainer = cookies;
request.ContentType = "application/json";
request.CookieContainer = cookies;
// write the "Authorization" header
request.Headers.Add("Authorization", "Basic " + api_token);
request.Method = "POST";
// get the response
//WebResponse response = request.GetResponse();
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
Debug.Log(reader.ReadToEnd());
}
I need the node wrappers to do authentication and the post request.
The node wrappers: c10. I've tried with this one a lot and
node-canvas-api
I can access the api and post using postman.
I found out I can use code snippets on postman to retrieve the request in a certain language. With this, I didn't need the python APIs anymore as I was able to get the code directly. I still don't know why Unity did not recognize restSharp, but python solved my problem.
As it was hard for me to find how to post grades and comments on Canvas lms I will leave the PATH here for anyone who has the same problem:
PUT /api/v1/courses/:course_id/assignments/:assignment_id/submissions/:user_id
the query params are:
comment[text_comment] and submission[posted_grade].

How to get redirect URL in dart/flutter?

I'm building an app that shows an image taken from source.unsplash. My request url is:
https://source.unsplash.com/random/`$widthx$height`
Then the service redirects to some specific image url picked fitting my width and height.
I can show the image with:
Image.network(url above),
but I cannot access the new redirected url for some other parts of my code which is really necessary. Is there a way to get it?
Thanks in advance
Something I'm searching for is like
Http.Response response = await Http.get(url);
print(response.finalRedirectURL);
It would be better if you use api.unsplash.com and not source.
If followRedirects is true, there's no way according to the docs to get the final redirected URL, so maybe post a github issue for this. See: https://pub.dev/documentation/http/latest/http/Response-class.html
The only way I see this happening is making followRedirects: false, will give you a response headers with location as a key that gives you the next redirect. You'd have to write a loop to keep going till the status code changes from 302 to something else.
Hope this helps.
For my own project, I was also not able to find any method from flutter/dart side.
However, I was able to find the location in response.headers. Maybe this can work.
Future<String?> getUrlLocation(String url) async {
final client = HttpClient();
var uri = Uri.parse(url);
var request = await client.getUrl(uri);
request.followRedirects = false;
var response = await request.close();
return response.headers.value(HttpHeaders.locationHeader);
}

contents not being added to the Fitnesse test/suite

I am trying to create new test page from REST api calls in Fitnesse. The page is being created but the contents is not being added.
I am using addChild responder.
here is my code.
DefaultHttpClient client = new DefaultHttpClient();
HttpGet post = new HttpGet("http://localhost:80/TestSuite?responder=addChild&pageName=RestSuite&pageType=Suite&content=valuetosave");
HttpResponse response = client.execute(post);
String str1 = EntityUtils.toString(response.getEntity());
System.out.println(str1);
I searched a lot but couldn't find any examples also.. please help.
Thanks in advance.
After lots of efforts I found that that documentation is wrong for Rest on fitness.org the parameter in the request is not 'content' but 'pageContent'...