Angular 5 Service httpClient Post - Title is not defined - javascript

I am trying to post so data from an angular 5 service.
In the service I have:
export class DataService {
title: 'My Title';
then
postIt() {
return this.httpClient.post<any>('http://jsonplaceholder.typicode.com/posts', title: 'sometitle');
}
and then from my app.cmponent.ts onInit I have:
this.myDataService.postIt()
.subscribe(
res => {
console.log(res);
},
err => {
console.log("Error occured");
}
);
I'm getting error:
ERROR ReferenceError: title is not defined
What I'm I doing wrong?

Post request accept second parameter as a json body which is an object. When you try to send any data in post call, it should be in object format
const body = {name: 'Brad'};
http
.post('/api/developers/add', body)
// See below - subscribe() is still necessary when using post().
.subscribe(...);
Below is the link for more details
https://angular.io/guide/http

Try like this :
postIt() {
return this.httpClient.post<any>('http://jsonplaceholder.typicode.com/posts', { title: 'sometitle' });
}

Related

Get token from URL and send to post api with Axios Vuejs

Hi i need to take token from URL http://192.168.178.25:8080/register?token=eyJhbGciOiJIUzI...
and send a Post request on API for confermation account
I have tried this but on backend i've receive SyntaxError!
Someone can help me?
<script>
import axios from 'axios'
export default {
name: 'Register',
data() {
return {
confirmation : false,
somethingWrong: false
}
},
created: function() {
axios.post('/api/users/validateRegister', null,{
params: {
registerToken: this.$route.query.token,
state: this.$route.query.state
}
})
.then((res) => {
console.log(res)
this.confirmation = true
})
.catch((err) => {
console.log(err)
this.somethingWrong = true
})
}
}
</script>
Your server is expecting JSON but you are sending something else.
Try running this in your browser console (devtools): JSON.parse('asdasd').
How you are sending it right now:
axios.post('/api/users/validateRegister', null,{
params: {
registerToken: this.$route.query.token,
state: this.$route.query.state
}
})
Will send a request that looks like:
/api/users/validateRegister?registerToken=<token>&state=<state>
To do a POST request with body according to docs, you do:
axios.post(url[, data[, config]])
Which in your case means, assuming you need registerToken and state as part of body and not query parameters:
axios.post('/api/users/validateRegister',{
registerToken: this.$route.query.token,
state: this.$route.query.state
})
Notice how there's no null in the 2nd param and no params: {}
You can also according to docs do the following syntax:
axios({
method: 'post'
url: '/api/users/validateRegister',
data: {
registerToken: this.$route.query.token,
state: this.$route.query.state
}
})
It looks like your server is throwing an error when trying to parse the body.
From your axios request, you're passing parameters instead of a body - you can see this by looking at the URL in the POST error on the right-hand side of your screenshot.
Instead, send the payload in the body like this;
axios.post('/api/users/validateRegister',
{
registerToken: this.$route.query.token,
state: this.$route.query.state
})
As you haven't provided any of the server-side code there may be something else going on we can't see.

Request Body Missing in Spring while updating using PATCH API in react js

Spring shows - Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public com.cg.bookstore.entities.OrderDetails com.cg.bookstore.controller.OrderDetailsController.updateDeliveryStatus(int,java.lang.String)]
Console shows - Uncaught (in promise) Error: Request failed with status code 400
class UpdateOrder extends Component {
state = {
deliveryStatus:""
}
handleChange = (event) => {
const deliveryStatus = { ...this.state.deliveryStatus };
this.setState({ deliveryStatus: event.target.value });
};
handleSubmit = (event) => {
// Prevents default behaviour of submit button
event.preventDefault();
console.log(this.state.deliveryStatus)
console.log()
OrderService.updateDeliveryStatus(this.props.match.params.orderDetailsId,this.state.deliveryStatus)
.then((res) => {
this.props.history.push("/admin/orders");
});
};
In OrderService I call the updateDeliveryStatus
async updateDeliveryStatus(orderId,deliveryStatus){
return await axios.patch(BASE_URL+"/"+orderId,deliveryStatus)
}
The updateDeliveryStatus service in spring
#Override
public OrderDetails updateDeliveryStatus(int orderId, String deliveryStatus)
{
Optional<OrderDetails> opt = orderDetailsRepo.findById(orderId);
OrderDetails od;
if (opt.isPresent())
{
od = opt.get();
od.setDeliveryStatus(deliveryStatus);
orderDetailsRepo.save(od);
} else
{
throw new OrderDetailsNotFoundException("Order is not found");
}
return od;
}
While I was testing backend in POSTMAN , I pass the input as plain string and it works fine. Is it because the input in not in form of json the issue? How to fix this ?
Usually, when using #PutMethod and wanting to update a resource you need to provide both ID of the resource you want to update and the new body, which in this case I presume is 'OrderDetails', error suggests is missing there.
Without java controller code it's only assumptions though.

Unable to customize form errors because server is returning 422 Unprocessable Entity without returning errors

I'm working with Laravel and VueJS and for all of my post and put methods server returns the newly created data after submitting the form, in the case of errors, I cannot access them from the browser console. This is what I can see in the newtwork tab.The purpose is to customize form errors according to errors that is being returned by the server
Here is my backend code :
private function validateForm($data){
return Validator::make($data,
[
'fname' => ['required', 'string','min:2' ,'max:255'],
'lname' => ['required', 'string','min:2' ,'max:255'],
// 'mname' => ['string','min:2' ,'max:255'],
'company' => ['string','min:2' ,'max:255'],
'title' => ['string','min:2' ,'max:255'],
'phone_number' => ['string','min:13' ,'max:13'],
'city' => ['required', 'string','min:2' ,'max:100'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed']
// 'password_confirm'=>['required','string']
]
)->validate();
}
//Register
public function register(Request $request){
$data=$this->validateForm($request->all());
$data['password']=Hash::make($data['password']);
$user=new User($data);
$user->save();
return response()->json($user);
}
And my code from the front-end:
export default{
data(){
return {
form:{
email:'',
password:'',
password_confirmation:'',
fname:'',
lname:'',
city:''
},
formError:''
}
},
methods:{
//This should be a POST method through axios
register:async function(){
try{
const res=await axios.post('api/register',
{
email:this.form.email,
password:this.form.password,
password_confirmation:this.form.password_confirmation,
fname:this.form.fname,
lname:this.form.lname,
city:this.form.city
});
//Une fois inscrit,il est redirige vers la page de login
this.$router.push({path:'/login'});
console.log("My data : ",res.data);
}catch(err){
console.log("Errors",err);
}
}
}
}
When there are no errors, everything goes fine, but when there are errors, this is what I get in the browser console tab:
And in the Devtools network tab
I've tried the following link Issues with Axios catch method from Laracast
how to display the errors in .catch coming from an api on frontend
And some others solution,but all of them didn't solve my problem.
Before using async-await pattern i used axios.post('url',data).then(res=>...).catch(err=>...)
When i use postman,http status is still 422 but the error object is returned,so with postman everything goes fine but not in the browser
How can i solve this problem?
Laravel returns the HTTP 422 - Unprocessable Entity when the validations you set fail. In your case I would take a closer look at the data you're posting to the server and manually check if it passes the validation cases you wrote.
To get the exact fields that are causing the error you need to handle this in your code, like this for example:
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
// 500 is the HTTP Status Code you want to return.
// This should also throw you in the catch branch of your front-end code
return response()->json(['errors'=>$validator->errors()], 500);
}
In your code the $data variable from the register function should be checked if it fails validation and return the error
This is because err will return the toString() method when accessed directly, but has properties:
err.response.data will have what you're looking for.
When there's an HTTP error (e.g. a response code between 400 and 599) axios returns an axios error response and in the repository documentation under error handling it indicates that you can access the actual response using error.response.data. For example:
try {
const res=await axios.post('api/register',
{
email:this.form.email,
password:this.form.password,
password_confirmation:this.form.password_confirmation,
fname:this.form.fname,
lname:this.form.lname,
city:this.form.city
});
//Une fois inscrit,il est redirige vers la page de login
this.$router.push({path:'/login'});
console.log("My data : ",res.data);
}catch(err){
if (err.response && err.response.status === 422) {
if (err.response.data.errors.fname) {
console.log('First name errors: '+ err.response.data.errors.fname.join(','));
}
// and so on
}
}
When Axios throws an error, the HTTP response can be found in error.response. Validation errors will be in the errors key, so you can access validation errors like this:
axios.post(someUrl, someData)
.then(response => {
// Successful response
})
.catch(error => {
let errors = error.response.data.errors;
});

problem with Display error messages in angular js

I need to display error message, when service issue.
i use below function to load data to the dropdown. function is loading in page load.
component
loadOrgNames(){
this.orgNameModel = this.dataserviceService.getOrgName();
}
service
getOrgName() : Observable<any> {
return this.http.get(this.orgnameurl);
}
how i handle errors in my service class.
the function getOrgName return an Observable, if the value is correct for dropdown use async pipe on your html. or use it like below:
this.dataserviceService.getOrgName().pipe(
tap(data => {
this.orgNameModel = data;
}))
This is how a service that returns Observable should be consumed.
Error should be handled like below:
loadOrgNames(){
this.dataserviceService.getOrgName().subscribe( response => {
this.orgNameModel = reponse;
},
errorResponse => {
});
}

Using Axios and Vue to fetch api data - returning undefined

Running into a snag with trying to integrate my API with Vue/Axios. Basically, Axios is getting the data (it DOES console.log what I want)... But when I try to get that data to my empty variable (in the data object of my component) to store it, it throws an "undefined at eval" error. Any ideas on why this isn't working for me? Thanks!
<template>
<div class="wallet-container">
<h1 class="title">{{ title }}</h1>
<div class="row">
{{ thoughtWallet }}
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'ThoughtWallet',
data () {
return {
title: 'My ThoughtWallet',
thoughtWallet: [],
}
},
created: function() {
this.loadThoughtWallet();
},
methods: {
loadThoughtWallet: function() {
this.thoughtWallet[0] = 'Loading...',
axios.get('http://localhost:3000/api/thoughts').then(function(response) {
console.log(response.data); // DISPLAYS THE DATA I WANT
this.thoughtWallet = response.data; // THROWS TYPE ERROR: Cannot set property 'thoughtWallet' of undefined at eval
}).catch(function(error) {
console.log(error);
});
}
}
}
</script>
Because you're using .then(function(..) { }) this won't refer to the vue context this.
You have two solutions, one is to set a variable that references the this you want before the axios call, e.g.:
var that = this.thoughtWallet
axios.get('http://localhost:3000/api/thoughts').then(function(response) {
console.log(response.data); // DISPLAYS THE DATA I WANT
that = response.data; // THROWS TYPE ERROR: Cannot set property 'thoughtWallet' of undefined at eval
}).catch(function(error) {
console.log(error);
});
The other is to use the new syntax (for which you need to make sure your code is transpiled correctly for browsers that don't support it yet), which allows you to access this inside the scoped body of the axios then.
axios.get('http://localhost:3000/api/thoughts').then((response) => {
console.log(response.data); // DISPLAYS THE DATA I WANT
this.thoughtWallet = response.data; // THROWS TYPE ERROR: Cannot set property 'thoughtWallet' of undefined at eval
}).catch(function(error) {
console.log(error);
});
The reason this happens is because inside that function/then, this will be referring to the context of the function, hence there won't be a thoughtWallet property
this.thoughtWallet inside the .get method is referring to the axios object, not Vue's. You can simply define Vue's this on the start:
methods: {
loadThoughtWallet: function() {
let self = this;
this.thoughtWallet[0] = 'Loading...',
axios.get('http://localhost:3000/api/thoughts').then(function(response) {
console.log(response.data); // DISPLAYS THE DATA I WANT
self.thoughtWallet = response.data;
}).catch(function(error) {
console.log(error);
});
}
}

Categories

Resources