I have a small problem with my Http Service in my Angular CLI app.
I have a form I need to submit. Data from this form are sent to API and stored into database.
This is the service
import {Injectable} from "#angular/core";
import {Http, Headers} from "#angular/http";
#Injectable()
export class HttpService {
private api: string = "http://localhost/api/www/";
constructor(private http: Http) {
}
insertRouteReview(data: {}) {
const headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
});
this.http.post(this.api+"route/addreview", data, {headers: headers});
}
}
Data sample:
{
"reviewId": 1,
"userId": 1,
"routeId": 1,
"ratio": 3,
"description": "lorem ipsumaaa"
}
Note: urlencoded is there before PHP cannot handle the application/json format.
When I send the data via some tool (For example Restlet Client) like this
The data are stored into DB successfully. So API should be fine.
What Am I doing wrong in my angular app? I get no error when I click the button which gets the data and pass them into http service.
E:
Code which is triggered after submit button is clicked
onSubmit() {
let review: {} = {
reviewId: +this.reviewForm.value.reviewId,
userId: +this.userService.userId,
routeId: +this.routeId,
ratio: +this.reviewForm.value.ratio,
description: this.reviewForm.value.description
};
this.httpService.insertRouteReview(review);
}
The review form is just form created in typescript and its working fine. If I dump values (or review object) I can see the proper values.
E: I subscribed to the post and now Its working fine. Thank you
The problem was I didn't subscribed to that post() method. When I did it, I reached the API.
Related
I'm getting a 400 error and isAxiosError: true. I think the problem is the auth line is not formatted correctly, or I'm not quite understanding how params work in axios and what's needed by the api? What am I doing wrong in my translating of python to Axios/JS?
Here's the Voila Norbert API documentation.
Here's my Axios api call.
axios.post('https://api.voilanorbert.com/2018-01-08/search/name', {
params: {
auth: {any_string: API_KEY},
data: {
domain: 'amazon.com',
name: 'Jeff Bezos'
}
}
})
Here's the python version:
API_TOKEN = 'abcde'
req = requests.post(
'https://api.voilanorbert.com/2018-01-08/search/name',
auth=('any_string', API_TOKEN),
data = {
'name': 'Cyril Nicodeme',
'domain': 'reflectiv.net'
}
)
I am a year late with this answer but I found your question while dealing with this same error with the same API. The API documentation's suggested Python code works for me with a successful response, but I want to do it in Node and the JS code returns a 400 error. I'm sharing my solution in case it helps others in the future.
I believe the core issue is that the API expects the data to be posted as form data, not as JSON. I followed an example in another post to post form data with Axios but still was receiving a 400 error.
Then I tried posting it using the request package instead of Axios, and that results in a successful response (no error):
const request = require('request');
var data = {'name': 'Jeff Bezos', 'domain': 'amazon.com'};
request.post({
url: 'https://any_string:API_KEY#api.voilanorbert.com/2018-01-08/search/name',
form: data,
}, function(error, response, body){
console.log(body);
});
This example works when the data is included in the form: field but does not work when it is in body:
Please note the request package is deprecated and in maintenance mode.
According to their documentation, https://github.com/axios/axios, you need to give auth as a separate field, not inside params:
axios.post('https://api.voilanorbert.com/2018-01-08/search/name', {
auth: {
username: 'any_string',
password: API_KEY
},
data: {
domain: 'amazon.com',
name: 'Jeff Bezos'
}
})
Updated: removed the nesting of data in params. They should be sent as POST body, not URL params.
I am working with Stripe (developing a payment system) on React.js and I am trying to translate the code below into React.js and use axios to create the endpoint that receives the POST request from the backend (Django):
var handler = StripeCheckout.configure({
key: 'pk_test_zNq2YI8Spsyi81TknNujN36T',
image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
locale: 'auto',
token: function(token) {
$.ajax({
type: "POST",
url: 'http://localhost:8000/subscriptions/codes/pay/',
data: {amount: amount, token: token},
});
}
});
I am stuck on Step 4 from this link : Stripe for React, which explains the POST request but they are using Express, and I am using Django.
The server side code can be written in any language/frameworks as long as it provides an endpoint subscriptions/codes/pay/ for your front-end post.
In Django, you can refer to the document at [0] on how to get started on creating a REST API
A very simple code
define your route
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('subscriptions/checkout', views.ElementView.as_view(), name="Stripe Checkout"),
path('subscriptions/codes/pay', views.charge, name='charge'),
]
And in your view definitions
from django.http import HttpResponse
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
#require_http_methods(["POST"])
#csrf_exempt
def charge(request):
# request.body will contain your data {amount: amount, token: token}
return HttpResponse(request.body)
Again, the backend implementation should be language/framework agnostic; it will work as long as your backend provide a valid POST API allowing you to send your StripeToken back
[0] https://docs.djangoproject.com/en/2.1/intro/tutorial01/
I want to call an http.post() request synchronously and after the response receive want to proceed with other code.
Or just want to hit the server but don't want to wait for the response.
Perhaps I'm just missing something, but that shouldn't be too hard if you're willing to ignore the response. If you're using angular, put somewhere at the top of your file:
import { HttpClient } from '#angular/common/http';
Then, in the constructor, include:
constructor(private http: HttpClient, ...) {
//...
}
Finally, in your code, just include the post request with an empty function after you get the result back:
this.http.post(url, requestBody, options).toPromise().then(() => {}).catch(error => {
console.error("Error: ", error);
});
Hope this helps!
I am developing an angular2+ app with typescript. I am trying to pull data for one of my Angular2 Kendo grid and making the following call to get results to populate the grid. In this web call I am sending a status ID , skip and take and a Sort array which contains the field I want to sort and the direction I want it sorted in.
Below is my typescript code which makes the web service call:
getUserRequests(statusId: number, skip: number, take: number, sort: SortDescriptor[]): Observable<GridResult> {
private getUserRequestsUrl = environment.serviceHostName + environment.serviceAppURL + '/api/Dashboard/GetUserRequestsByStatuses';
var headers = new Headers();
headers.append('Content-Type', 'application/json;');
return this.http.post(this.getUserRequestsUrl, JSON.stringify({ "Filter": { "Field": "StatusId", "Value": statusId, "Operator": "eq" },
"Skip": skip, "Take": take, "Sort": sort }), { headers: this.headers }).share()
.map((res: Response) => res.json())
.map(response => (<GridResult>{
data: response.Data ,
total: response.Count
}));
}
This is my service side code which never gets hit.
[HttpGet]
public HttpResponseMessage GetUserRequestsByStatuses([FromBody] DataRequest model)
{
DataResponse<AngKendoGridDashboard> response =
BusinessAccess.GetUserRequestsByStatuses(model);
return CreateHttpResponse(response);
}
Problem I am facing:
For some reason when make this web service call I get an error saying
"ERROR Response with status: 405 Method Not Allowed for URL:
http://localhost/Services/RequestService/api/Dashboard/GetUserRequestsByStatuses"
I checked the request object which is being sent and here is what is looks like
{"Filter":{"Field":"StatusId","Value":2,"Operator":"eq"},"Skip":0,"Take":5,"Sort":[{"field":"CreatedDate","dir":"desc"}]}
Also in the response body I see this message:
{"Message":"The requested resource does not support http method
'POST'."}
I been looking at this since Friday and could not come up with a solution. Any help is appreciated. I think it may be something to do with how I am sending my request object through typescript.
The error says the method POST is not supported yet the action has a HttpGet attribute.
You'll need to change the HttpGet to HttpPost.
[HttpPost]
public HttpResponseMessage GetUserRequestsByStatuses([FromBody] DataRequest model)
{
DataResponse<AngKendoGridDashboard> response =
BusinessAccess.GetUserRequestsByStatuses(model);
return CreateHttpResponse(response);
}
You could also lose the [FromBody] attribute too, it's the default given the parameter type.
I am trying to set my auth token recieved from the response after user registration into Ember Data request header.
Here is my application.js code
import DS from 'ember-data';
export default DS.RESTAdapter.extend({
namespace: 'merchant',
host: 'http://192.168.1.173:3000',
headers: function() {
return {
"token":localStorage.token,
};
}.property("localStorage.token","token")
});
I am trying to set the header after receiving success response from my register user API call.
var register=this.store.createRecord('registermerchant',data);
register.save().then(function(response){
console.log(response.success);
if(response.get('success')){
self.set('token',response.get('token'));
self.transitionToRoute('merchanthome')
}
and
tokenChanged: function() {
localStorage.token=this.get('token');
console.log(localStorage.token);
}.observes('token'),
I am able to see the updated localStorage.token value however this value for some reason does not get set to the reqest header token key.
The token is not getting updated to the header , it is only after doing a page refresh that the new updated token is being sent to the server.
Any thoughts on what I could be doing wrong,any tips would be greatly appreciated.
Thanks
localStorage is not an observable Ember object, so your property("localStorage.token") will only be evaluated once. Instead make it volatile to re-evaluate the property every time:
headers: function() {
return {
"token":localStorage.token,
};
}.property().volatile()