How to get response from API using Angular 9 http post request - php

I am using Postman to make POST request to API and save data to DB and I am getting as response {message:"Contact created successfully"}. BUT in Angular I don't get any response. What I am doing wrong?
I have provided a piece of my code below.
Angular Service
add(contactItem: any){
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
const contactApiUrl = "url to api/addContact.php";
return this.http.post(contactApiUrl,contactItem, httpOptions).pipe(
map( (response: any) => { console.log(response); }),
catchError(this.handleError)
);
}
Contact.component.ts
//here from the form I pass the data to service add()
onSubmit(contactData){
console.log(contactData);
this.contactService.add(contactData).subscribe();
//this.contactLst = this.contactService.get();
}
addContact.php
//more code here
// create the product
if($contact->create()){
// set response code - 201 created
http_response_code(201);
// tell the user
echo json_encode(array("message" => "Contact was created."));
}
// if unable to create the contact, tell the user
else{
// set response code - 503 service unavailable
http_response_code(503);
// tell the user
echo json_encode(array("message" => "Unable to create contact."));
}
Any help is welcome.

You're not actually returning the response. You are only logging it:
add(contactItem: any){
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
const contactApiUrl = "url to api/addContact.php";
return this.http.post(contactApiUrl,contactItem, httpOptions).pipe(
map( (response: any) => response ), // <- return response
catchError(this.handleError)
);
}
To call it, you need to specify what happens in your subscribe callback:
//here from the form I pass the data to service add()
onSubmit(contactData){
console.log(contactData);
this.contactService.add(contactData).subscribe( r => console.log(r) );
//this.contactLst = this.contactService.get();
}

Related

Angular HTTP POST request doesn't create anything

I'm using Angular with PHP and trying to post an object. Request status is 200, but $_POST array is empty. Data I'm sending is a valid JSON Object.
sendTweet(){
if(!this.username || !this.tweet){
alert("Enter username or tweet");
return;
}
const newTweet:Tweet = {
username: this.username,
tweet: this.tweet
}
//Call Service
this.testService.postTweet(newTweet).subscribe((response)=>{console.log(response)},
(err:any)=>{
console.log(err.message);
});
}
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
postTweet(tweet:Tweet):Observable<Tweet>{
const url = `${this.apiUrl}/?page=submit&action=add`;
return this.http.post<Tweet>(url,tweet, httpOptions);
}
PHP:
if (isset($_POST['tweet'])&&isset($_POST['username'])) {
//Sending tweet to the db
} else{
print_r($_POST);
}
i dont know if its a backend problem with php but in my project i have it a little bit diferent (i am using .net core for backend)
for example in my project:
//service component WebScrapLinkService
get(): Observable<Any[]> {
return this.http.get<Any[]>(this.url)
.pipe(map(res => res));
}
//main component
getRegisters() {
this.getProductsSub = this.crudService.get()
.subscribe(data => {
this.registers = data;
})
}
//variables
public registers: Array<object> = [];
//the service goes in the constructor
private crudService: WebScrapLinkService
this works fine for me, i hope it is useful for you
It was just me not knowing that in PHP you have to parse HTTP_RAW_POST_DATA in order to get the data.

Add additional data to request object after initialisation

The below public function returns oauth token against user name and password. However, I have a requirement where, the username has to queried first from email id. In the first part of the function, I need to somehow add the username to the request object. The request is created using laminas from what I can understand.
Full code from which function is taken is here.
/**
* Processes POST requests to /oauth/token.
*/
public function token(ServerRequestInterface $request) {
////////////////
////////////////
// ADD LOGIC TO GET EMAIL FROM REQUEST & GET USERNAME
// ADD USERNAME TO $request
////////////////
////////////////
//Extract the grant type from the request body.
$body = $request->getParsedBody();
$grant_type_id = !empty($body['grant_type']) ? $body['grant_type'] : 'implicit';
$client_drupal_entity = NULL;
if (!empty($body['client_id'])) {
$consumer_storage = $this->entityTypeManager()->getStorage('consumer');
$client_drupal_entities = $consumer_storage
->loadByProperties([
'uuid' => $body['client_id'],
]);
if (empty($client_drupal_entities)) {
return OAuthServerException::invalidClient($request)
->generateHttpResponse(new Response());
}
$client_drupal_entity = reset($client_drupal_entities);
}
// Get the auth server object from that uses the League library.
try {
// Respond to the incoming request and fill in the response.
$auth_server = $this->grantManager->getAuthorizationServer($grant_type_id, $client_drupal_entity);
$response = $this->handleToken($request, $auth_server);
}
catch (OAuthServerException $exception) {
watchdog_exception('simple_oauth', $exception);
$response = $exception->generateHttpResponse(new Response());
}
return $response;
}
The request is send as form data:
See example js code below:
(username is accepted, email param is added to demonstrate whats needed)
var formdata = new FormData();
formdata.append("grant_type", "password");
formdata.append("client_id", "828472a8-xxxx-xxxx-xxx-ab041d3b313a");
formdata.append("client_secret", "secret-xxx-xxx-xxx");
//formdata.append("username", "username");
formdata.append("email", "email#email.com");
formdata.append("password", "password");
var requestOptions = {
method: 'POST',
body: formdata,
redirect: 'follow'
};
fetch("{{base_url}}oauth/token", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));

TypeError: Network request failed using fetch ReactNative and Laravel response

I am posting data to Laravel and expect a success response, but it catches the exception TypeError: Network request failed. Using get methods and login post methods using Laravel passport works all fine.
Adding 'Content-Type': 'application/json' to headers creates Network request failed for the login methods.
Postman returns valid errors or success, so works totally as expected.
Debugging showed that the request has been sent to Laravel and routing is correct as Visual Studio Code debugger stops at a breakpoint at return response.
public function postMessages()
{
...
return response()->json(['success' => 'success'], 200);
}
Route::middleware('auth:api')->group(function () {
Route::post('messages', 'Api\ChatController#postMessages');
});
export const fetchApi = async (endPoint, method = 'get', body = {}) => {
const accessToken = authSelectors.get().tokens.access.value;
const accessType = authSelectors.get().tokens.access.type;
let headers = {
...(accessToken &&
{
Authorization: `${accessType} ${accessToken}`
}
)
};
let response;
if (method=='get' || Object.keys(body)==0 ) {
response = await fetch(`${apiConfig.url}${endPoint}`, {
method: method,
headers: headers
});
} else {
var formData = new FormData();
Object.keys(body).forEach(type => {
formData.append(type, body[type]);
});
response = await fetch(`${apiConfig.url}${endPoint}`, {
method: method,
headers: headers,
body: formData
});
console.log('fetch response: ' + JSON.stringify(response));
}
let responseJsonData = await response.json();
return responseJsonData;
}
export const postMessages = (eidug, type, name, messages) => fetchApi('/message', 'post', {
'eidug': eidug,
'type': type,
'name': name,
'messages': messages
});
I expect a response without any exception like Postman. What can be going wrong?
Have you enabled CORS in the backend? Once open inspect->network and then run fetch. Show if there are any errors.

PHP Webhost Operation Checking

I wanted perform checking if the PHP Webhost is complete whenever perform a update function, if everything doing fine then send an notification and let the Application know the Operation is Doing fine.
Basically I wanted to know if the query in PHP work and use my application to notify the user.
is there any way or method to do so?
I using this method to fetch data from PHP in my React Native App
RecipeUpdation = () =>{
const { ID } = this.state ;
const { Name } = this.state ;
const { Type } = this.state ;
const { Ingredient } = this.state ;
const { Step } = this.state ;
return fetch('https://www.update.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
RecipeID : ID,
RecipeName : Name,
RecipeType : Type,
RecipeIngredient: Ingredient,
RecipeStep: Step
})
}).then((response) => response.json())
.then((responseJson) => {
}).catch((error) => {
console.error(error);
});
}
Basically we can verify if the Operation in PHP is successful or not by Checking the Query Execution Status. A very Basic way to do the checking is using If Else to see if the Query Function return True(Success) or False(Fail). You can also always return some Message through JsonResponds.
Here some example Code for PHP checking and Return Some Message:
// Using If Else to Check if operation Success or Not
if(mysqli_query($connection,$Your_Query)){
$MSG = 'Success' ;
// Convert message into Json format first
$json = json_encode($MSG);
// This is where it return the message to Application.
echo $json ;
}
else{
$MSG = 'Failed' ;
$json = json_encode($MSG);
echo $json ;
}
In your Application Code you already have the implementation to retrieve the JsonResponds(the Message) which have been echo in the PHP Code, I would suggest use a simple method which is Alert to pop out the message in your React Native Application to notify the User the Operation Status.
}).then((response) => response.json())
.then((responseJson) => {
// this responseJson Already have the echo Message from PHP
// just Display the Status with Alert Function
Alert.alert(responseJson);
}).catch((error) => {
console.error(error);
});
Hope this would help.

Ionic2 / Angular2 MailChimp API GET response

Okey so I've got a little problem with MailChimp response. So here is the thing.
I want to check the status of the subscribed user. I have the PHP code which is works fine and i have the code which is also works fine so I get the response BUT I can't use the response after it. So here is the codes:
I have a MailService provider which contain this function:
postCheck(post: {email: string}): Observable<any>{
const email = JSON.stringify(post);
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-urlencoded');
return this.http.post('http://localhost:8100/getapi', email, {
headers: headers
}).map(res => {
console.log(res.json())
return res.json(); //add this line
});
}
In the main page I have this function:
sendCheck(email: string){
this.mailservice.postCheck({email: email})
.subscribe(
response => this.response = response.status,
error => console.log(error)
);
}
In the main page html when i call <p>{{ response }}</p> it write out 'pending' or 'subscribed'. But after it when I try console.log(this.response); it write out nothing so in the code I can't really do the checking.
From what I can gather, you want to do something with your response after the data has arrived. This you need to do inside the subscription, to ensure that the data is available. So something like this:
sendCheck(email: string){
this.mailservice.postCheck({email: email})
.subscribe(response => {
this.response = response.status;
// here the value has been set to response, so do what you want
this.doSomethingWithResponse();
)};
}
doSomethingWithResponse() {
if(this.response == 'subscribed') {
// do stuff
}
}

Categories