i tried to get my json data into my view using vuejs. i tried with api token. i generate a token with user register and saved it in a database row.
this is my controller
public function index()
{
$contact = Contact::all();
$contactcount = count($contact);
return json_encode([
'contactcount' => $contactcount,
]);
}
and this is my vue js method
fletchDetails(){
fetch('http://slfsnew.test/api/contact', {
params: {
api_token: this.api_token,
}
})
.then(res => res.json())
.then(res => {
this.contact = res.contactcount;
});
},
i tried to get my api token with a prop
data(){
return {
contact: '',
uri: 'http://slfsnew.test/api/contact',
api_token: this.user.api_token,
}
}
and i define my vuejs component like this.
<contactform #if(auth()->check())
:user="{{ auth()->user() }}"
#endif></contactform>
this api token gets my data property and finally it shows me this error.
admin:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at
position 0
how can i fix this. i want to get my count and shows it in a bootstrap card
<h3>{{ contact }} test</h3>
Related
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.
I am Working at a VueJS Webapplication with a c# WebAPI in the background. I made already one endpoint but I cant get it to work. The body of the response is always null. When i check the debug section on the network tab, i can see the message i want to get in the preview section, but I cant get it to show on the page.
VueJS component:
<template>
<div class="dashboard">
<button type="button" id="get-joke" #click="fetchAPIData">Get a Joke!!</button>
<div v-if="responseAvailable == true">
<hr>
<p>
<i>{{result}}</i>
</p>
<hr>
</div>
</div>
</template>
<script>
export default {
name: 'Dashboard',
props: {
msg: String
},
components: {
},
Data() {
result: null,
responseAvailable: null
},
methods: {
fetchAPIData() {
this.responseAvailable = false;
fetch("https://localhost:44322/api/values", {
"mode": "no-cors",
"method": "GET",
})
.then(response => {
alert(response); //checking if i get something
return response.json();
})
.then(response => {
this.result = response.body;
this.responseAvailable = true;
})
.catch(err => {
var error = err;
return error;
});
}
}
};
</script>
C# API Controller (returning a JSON string of a list of Objects) :
using System;
using Microsoft.AspNetCore.Mvc;
using MO_Backend.Services;
using MO_Backend.APIServices;
namespace MO_Backend.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly O_UserService _oUserService;
public ValuesController(O_UserService oUserService)
{
_oUserService = oUserService;
}
// GET: api/values
[HttpGet]
public String Get()
{
OnlineCheckService occ = new OnlineCheckService(_oUserService);
return occ.GetRobotState();
}
}
}
Does anyone know what im doing wrong or an alternative to what im trying to do?
The problem is the no-cors mode in your http request. This results in an opaque request, which means you get a response, but you cannot use the data. You need to use cors and set the response headers in your backend accordingly.
I am trying to use Vue.js for my front end to call Stripe and create a token which then is sent to my backend. I have tested everything using plain HTML/JS and it all works fine, my issue comes in trying to use Vue.js I think my issue might be in how I am binding the stripe public key. Below is my code, and I have zero output to speak of, I get just redriected to the same page but wth ? at the end of the URL. Nothing else, console shows nothing and no error message or anything send to my back end.
template code
There is more but not related
<div class="col-md-8">
<card class='stripe-card col-md-8'
:class='{ complete }'
:stripe='stripeKey'
:options='stripeOptions'
#change='complete = $event.complete'
/>
<button class='pay-with-stripe' #click='pay' :disabled='!complete'>Submit Payment Details</button>
<br>
</div>
script section with relavent added
import { Card, createToken } from 'vue-stripe-elements-plus'
import axios from 'axios';
export default {
components: { Card },
data() {
return {
errorMessage: null,
successMessage: null,
complete: false,
stripeKey: process.env.VUE_APP_STRIPE_PUB_KEY,
stripeOptions: {
// see https://stripe.com/docs/stripe.js#element-options for details
hidePostalCode: true
},
current: {
stripe: {
plan: null,
last4: null
}
},
}
},
methods: {
pay () {
createToken().then(result => {
axios.post('/billing/updateCard', {
token: result.token,
})
.then(res => {
if(res.data.success == true) {
this.successMessage = res.data.message
console.log(res.data.message)
}
if(res.data.success == false) {
this.errorMessage = res.data.message // Display error message from server if an error exists
}
})
.catch((err) => {
if(err) console.log(err)
if(err) this.$router.push('/company/settings?success=false')
})
});
}
}
}
</script>
I have checked that the API key is actually in the data value by doing <p>{{ stripeKey }}</p> and seeing the value show up. So yes the key is there and the key is valid (tested copy/paste into my HTML/JS test)
created(){
this.key=process.env.VUE_APP_STRIPE_KEY;
}
try this, i used this piece of code in my project and it worked... the issue maybe is that your key is not yet initialized when card us rendered idk. maybe key isnt issue at all. try this and let me know if works and we will debug it together.
i am trying to show some table data in view using vue js and laravel :
here is what i have tried :
this is comment controller :
public function index()
{
$comment = Comment::Latest()->paginate(10);
return new CommentResource($comment);
}
here is my vue js comment script
export default {
data: function() {
return {
comments: {}
}
},
created() {
this.loadComments();
}
,
methods: {
loadComments(){
axios.get("../api/comment").then(
({ data })=>(this.comments - data.data)
// response => this.comments = response.data
);
},
}
}
and finally the html part of vue html
<div v-for="comment in comments" >
{{ comment.title }}
</div>
the result is this error i get in browser :
[Vue warn]: Error in render: "TypeError: Cannot read property 'title' of undefined"
and here
[Vue warn]: Property or method "comment" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
and
TypeError: Cannot read property 'title' of undefined
btw i am sure that i have this because this is my api that i recice on
http://localhost:8000/api/comment
{"current_page":1,"data":[{"id":1,"title":"asd","body":"asd","user_id":1,"user_email":"asd","status":1,"created_at":null,"updated_at":null}],"first_page_url":"http:\/\/localhost:8000\/api\/comment?page=1","from":1,"last_page":1,"last_page_url":"http:\/\/localhost:8000\/api\/comment?page=1","next_page_url":null,"path":"http:\/\/localhost:8000\/api\/comment","per_page":10,"prev_page_url":null,"to":1,"total":1}
and when i console log this :
axios.get("../api/comment").then(({ data }) => (console.log(data)))
i get this result :
You're already extracting data from the response. So either you use the response object like this :
axios.get("../api/comment").then((response) => (this.comments = response.data.data)));
Or you extract the data property and use it.
axios.get("../api/comment").then(({ data }) => (this.comments = data.data)));
This is because axios returns a response object that has a data property that contains the server response. As your server response also has a data property that you want to use, you want to use response.data.data
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' });
}