Angular2 Http post 400 - json

I have this service:
#Injectable()
export class HttpserviceService {
baseUrl: string = "http://localhost:3000/";
headers = new Headers({
'accept': 'application/json'
});
post(url: string, data: any): Observable<any> {
//send post request
return this.http.post(this.baseUrl+url, JSON.stringify(data))
.map(this.extractData) //this works
.catch(this.handleError); //this as well
}
}
and when I subscribe to that method:
user: User = {
username: "test",
password: "12345"
}
authUrl: string = 'user/auth';
return this.http.post(this.authUrl, user)
.subscribe(data => {
//console.log(data);
});
I'm getting an
Status Code:400 Bad Request
What can be wrong?
When I request using postman everything works ok

In postman i see that you have 1 header. Which you are not sending in angular
Try following, headers should go as a third parameter
post(url: string, data: any): Observable<any> {
//send post request
return this.http.post(this.baseUrl+url, JSON.stringify(data), {headers: this.headers})
.map(this.extractData) //this works
.catch(this.handleError); //this as well
}

Related

I need to fetch API to get a raw value from response same as the result in POSTMAN but fail?

I am new from here. Just stuck on some problem of fetching the data from frontend(react) to the raw value in JSON. For the login part, when I enter the email and password, supposedly the response are same as the result in POSTMAN, but i get the error. I am figure out this issue for almost oneweek. I would be appreciate for those who help me to solve on this issue. I will elaborate further on below about my situation:
Here is the response of API from postman (supposedly I should get this response):
The result I get in the browser:
Source Code:
constructor (props){
super(props);
this.state ={
loginEmail: '',
loginPassword: ''
}
this.login = this.login.bind(this);
this.onChange = this.onChange.bind(this);
}
login(){
PostData('api/users/login', this.state).then ((result) => {
let responseJSON = result;
console.log(responseJSON);
});
}
PostData:
export function PostData(type, userData = {}){
let BaseUrl = "https://ems-unimas-58134.herokuapp.com/"
return new Promise((resolve, reject) => {
fetch(BaseUrl+type,{
method: "POST",
body: JSON.stringify(userData),
Accept: 'application/json',
// headers:{
// 'Content-Type': 'application/json'
// }
}).then(res => res.json())
.then((responseJson) => {
resolve(responseJson);
})
.catch((error)=>{
console.error('Error:', error);
})
});
}
Commend down here if anyone of you need more code.
The problem is you need to allow CORS.
You can read more about CORS in here

Angular 2 Service Not Returning JSON from HTTP Response

I'm attempting to return JSON data from a web api, the service collects this fine and when you output this to the console it works and returns what I expect, but when I try to return the data to somewhere outside the service I can only get back 'undefined' with no errors.
Service Method
// Dashboard API Services
getModules() {
this._http.request(this._baseUrl + "Modules/Get").subscribe((res: Response) => {
this.modules = res.json();
});
return this.modules;
}
Service Call (in component)
import { Component, OnInit } from '#angular/core';
import { KoapiService } from '../koapi.service';
import { Http } from "#angular/http";
#Component({
selector: 'app-nav',
templateUrl: './nav.component.html',
styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {
modules: any;
constructor(private _koapi: KoapiService) { }
ngOnInit() {
this.modules = this._koapi.getModules();
console.log(this.modules);
}
}
Found a great article on much better way to do this here: https://hassantariqblog.wordpress.com/2016/12/03/angular2-http-simple-get-using-promises-in-angular-2-application/
Changed my code to the following, meaning the service can take any URL now from from the service call as opposed to inside the service:
Service Method(s):
// On successful API call
private extractData(res: Response) {
let body = res.json();
return body || {};
}
// On Erronious API Call
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
// Basic Get
getService(url: string): Promise<any> {
return this._http
.get(this._baseUrl + url)
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}
Service Call:
// Get Enabled Modules
this._koapi
.getService("Modules/Get")
.then((result) => {
this.modules = result;
console.log(this.modules);
})
.catch(error => console.log(error));
}
1.
const headers = new Headers({
'Content-Type': 'application/json',
'Cache-control': 'no-cache',
Expires: '0',
Pragma: 'no-cache'
});
const options = new RequestOptions({ headers: headers });
You have to send this 'options' along with url.

Angular 2 is removing JSON curly braces on HTTP POST response

Hello I have an issue where I am making a POST request to an API in Angular 2 and when I make the HTTP call, the Angular 2 returns a response, but instead of the expected JSON response, it returns a response in plain text with all the curly braces removed.
Example:
instead of {"type" : "string"} I get "typestring".
Here is my code:
let headers = new Headers({ 'content-type': 'application/json' });
let options = new RequestOptions({headers: headers});
this.http.post('api url', body, options).subscribe(data => console.log(data));
I understand there is a data.json() function but when I try that it just gives a
Unexpected token N in JSON at position 0 error.
Any help is appreciated, thanks.
try this
service.ts
import { Observable } from 'rxjs/Rx';
#Injectable()
export class MyService {
createRecored(body: any): Observable<any> {
let headers = new Headers({ 'content-type': 'application/json' });
let options = new RequestOptions({headers: headers});
this.http.post('api url', body, options)
.map(res => res.json())
.catch(error => Observable.throw(error));
}
}
component.ts
export class MyComponent {
constructor(private myService: MyService ) {}
doPost() {
this.myService.createRecored(body)
.subscribe(data => {
console.log('data', data);
}
}
}

Running Angular 4 app using a JSON server

I'm trying to run an Angular 4 app while trying to use a JSON server that it has been coded with. The problem I'm having is that I don't understand how an Angular 4 app running on port 4200 can communicate with the JSON server on port 3000 at the same time. The app is an example of CRUD but when I try to add something, nothing gets posted.
This is my article.service.ts:
#Injectable()
export class ArticleService {
//URL for CRUD operations
articleUrl = "http://localhost:3000/articles";
//Create constructor to get Http instance
constructor(private http:Http) {
}
//Fetch all articles
getAllArticles(): Observable<Article[]> {
return this.http.get(this.articleUrl)
.map(this.extractData)
.catch(this.handleError);
}
//Create article
createArticle(article: Article):Observable<number> {
let cpHeaders = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: cpHeaders });
return this.http.post(this.articleUrl, article, options)
.map(success => success.status)
.catch(this.handleError);
}
//Fetch article by id
getArticleById(articleId: string): Observable<Article> {
let cpHeaders = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: cpHeaders });
console.log(this.articleUrl +"/"+ articleId);
return this.http.get(this.articleUrl +"/"+ articleId)
.map(this.extractData)
.catch(this.handleError);
}
//Update article
updateArticle(article: Article):Observable<number> {
let cpHeaders = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: cpHeaders });
return this.http.put(this.articleUrl +"/"+ article.id, article, options)
.map(success => success.status)
.catch(this.handleError);
}
//Delete article
deleteArticleById(articleId: string): Observable<number> {
let cpHeaders = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: cpHeaders });
return this.http.delete(this.articleUrl +"/"+ articleId)
.map(success => success.status)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body;
}
private handleError (error: Response | any) {
console.error(error.message || error);
return Observable.throw(error.status);
}
}
This is my db.json:
{
"articles": [
{
"id": 1,
"title": "Android AsyncTask Example",
"category": "Android"
}
]
}
I have backend service running on port 5005, and app running on 4200, in order to "talk" with each other I have set up proxy.config.json file which looks like this
{
"/api/*":{
"target":"http://localhost:5005",
"secure": false,
"logLevel": "debug"
}
}
and when I serve my app I run
ng serve -open --sourcemap=false --proxy-config proxy.config.json command.
You can also try to do something like this.

post data in angular2

I am facing the issue of json added being added to the url after calling the service to add the data.
below is my file
first.ts
CreateNew(): void {
this.router.navigate(['/detail', 0]);
}
detail.ts
Submit() {
let templateId;
this.route.params.subscribe(
(param: any) => {
templateId = +param['templateid']; });
if (templateId === 0) {
this.jobservice.addJob(this.job).subscribe(error => this.errorMessage = <any>error);
}
this.router.navigate(['/template']);
}
service.ts
addJob(job: Job): Observable <Job> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
console.log(job);
return this.http.post('http://sample/api/Product/AddProduct', JSON.stringify(job), options).map(this.extractData).catch(this.handleError);
}
I am not able to find the issue why it is adding the json data to the url.
When you use the RequestOption, you dont use the method post, get, put or delete. But you use "request". Here is a sample request that works:
post<RQ, RS>(url: string, request: RQ, responseType: RS, withToken: boolean): Promise<RS> {
let postReq: Request = this.createAuthorizationHeader<RQ>(url, request, RequestMethod.Post, withToken);
return this.http.request(postReq).toPromise()
.then(res => {
return this.processingData<RS>(res, responseType);
})
.catch(this.handleError);
}
Then here you add your header to the request:
/**
* This function updates the token in the header
*/
createAuthorizationHeader<RQ>(url: string, requestData: RQ, method: RequestMethod, withToken: boolean) {
let headers = new Headers();
let options = new RequestOptions({
method: method,
url: url
});
/**
* Include token when boolean is passed
*/
if (withToken) {
headers.append('token', token);
options.headers = headers;
}
/**
* create bosy for post and put
*/
if (method === RequestMethod.Post || method === RequestMethod.Put) {
// do something
}
let request = new Request(options);
return request;
}
This should work, remember to use "http.request.." when you use request options
import { Http, Request, Response, Headers, RequestMethod, RequestOptions } from '#angular/http';
...
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({
method: RequestMethod.Post,
url: url,
headers = headers,
body: job
});
let request = new Request(options);
console.log(options);
return this.http.request(options).map(this.extractData).catch(this.handleError);
The issue was that while refresh of page it was showing 404 error.
In app.module.ts
Add imports: import { HashLocationStrategy, LocationStrategy } from '#angular/common';
And in NgMoudle provider, add: {provide: LocationStrategy, useClass: HashLocationStrategy}
which fixed the issue.
This should be working out fine. I have this working on my environment using angular 2.1.0.
import { Http, Request, Response, Headers, RequestMethod, RequestOptions } from '#angular/http';
...
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({
method: RequestMethod.Post,
url: 'localhost:51293/template',
headers = headers,
body: job
});
let request = new Request(options);
console.log(options);
return this.http.request(options).map(this.extractData).catch(this.handleError);