displaying data from restful service in react UI through nodejs - javascript

I've developed a restful webservice which displays a simple data using below code.
package com.mike;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class MessageController {
#RequestMapping(value="/message",method=RequestMethod.GET)
public Message print(){
return new Message(1,"Hello Mike!!");
}
}
and the bean is as follows....
package com.mike;
public class Message {
private int id;
private String message;
public Message(int id, String message){
this.id=id;
this.message=message;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMesssage(String message) {
this.message = message;
}
}
now I want to display this data in an Nodejs application, so I wrote a file named app.js and wrote the following code to display data in the console.and it worked fine. but i don't know how to integrate this nodejs application with reactjs UI so that i can display in on a web page. so please kindly help me, I am new to both node and react.the code for app.js is below...
var http=require('http');
var extServerOptions={
host:'localhost',
port:'8080',
path:'/message',
method:'GET'
};
var mes=[];
var x;
var text="";
function get(){
http.request(extServerOptions,function (res){
res.setEncoding('utf8');
res.on('data',function(data){
mes=JSON.parse(data);
console.log(mes);
for(x in mes){
text+=mes[x]+" ";
};
console.log(text);
});
}).end();
};
get();
please kindly say me the stepps i need to do in order to display data in a react page.

Related

Spring Book Rest API calling from Simple HTML and JavaScript and getting CROS error for HTTP DELETE request using XMLHttpRequest

I created a rest API for Library System which is doing CRUD operation and I tested it using POSTMAN and it is working fine. Now I want to display the result in a web page running in different ports in localhost using GO Live feater in VSCode.
Api running in "https://localhost:8081" mypage-> "https://localhost:5500". I did GET and POST using JavaScript by XMLHttpRequest and displayed the result on my webpage but in the case of DELETE it is showing and cross error but I annotated my class with #CrossOrigin.
Please give a details explanation as I am a newbie in Spring Boot.
Main Class:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.CrossOrigin;
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Controller Class:
package com.example.demo.Controler;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
#CrossOrigin
public class Topics
{
#Autowired
LibraryService libraryService;
//Get All Books
#RequestMapping("/books")
public List<Books> getAllBooks()
{
return libraryService.getAllBooks();
}
//Get Book by ID
#RequestMapping("/books/{id}")
public Books getBook(#PathVariable("id") int id)
{
return libraryService.getBookByID(id);
}
//Add Book Details
#RequestMapping(method = RequestMethod.POST , value = "/books")
public List<Books> addBook(#RequestBody Books book)
{
return libraryService.addBookDetails(book);
}
//Update Book details
#RequestMapping(method = RequestMethod.PUT, value="/update/{id}")
public List<Books> updateBookDetails(#RequestBody Books book,#PathVariable("id") int Id)
{
return libraryService.updateById(book, Id);
}
//Delete book by ID
#RequestMapping("/delete/{id}")
public List<Books> deleteBookByID(#PathVariable("id") int id)
{
return libraryService.deleteBookByID(id);
}
}
Service Class:
package com.example.demo.Controler;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Service;
#Service
public class LibraryService
{
List<Books> books =new ArrayList<Books>(Arrays.asList(
new Books(1, "Java", 10),
new Books(2, "C++", 111),
new Books(3, "Python", 11)
));
public List<Books> getAllBooks()
{
return books;
}
public Books getBookByID(int id)
{
return books.stream()
.filter(book->book.getId() == id).findFirst().get();
}
public List<Books> addBookDetails(Books book)
{
books.add(book);
return books;
}
public List<Books> updateById(Books book,int id)
{
Books bookUpdate = books.stream().filter(b ->b.getId() == id).findFirst().get();
books.set(books.indexOf(bookUpdate), book);
return books;
}
public List<Books> deleteBookByID(int id)
{
books.removeIf(b->b.getId() == id);
return this.books;
}
}
JS Code For Delete Request
(function(){
const xhr = new XMLHttpRequest();
xhr.open("DELETE","http://127.0.0.1:8081/books/1");
xhr.onload = ()=>{
console.log(xhr.response);
}
xhr.send(null);
})();

How to display data from a .NET Controller to React view?

I am trying to learn how to use .NET and React and make a single page application where the React front end speaks to the .NET back end. I have decided to create a simple thermostat application where the user can view a thermostat temperature and press buttons which will increase and decrease that temperature. Before I even get that far though I am struggling to get the data from my Controller class to display on my front end. Here is my code:
ThermostatController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace ThermostatDotNet.Controllers
{
[Route("api/[controller]")]
public class ThermostatController : Controller
{
private int _Temperature { get; set; }
public ThermostatController(int _temperature)
{
_Temperature = _temperature;
}
[HttpGet, Route("GetTemp")]
public int GetTemp()
{
return _Temperature;
}
[HttpGet, Route("Increase")]
public int Increase()
{
_Temperature += 1;
return _Temperature;
}
}
}
Thermostat.js
import React, { Component } from 'react';
export class Thermostat extends Component {
state = {
temp: ""
}
displayTemp() {
fetch("api/Thermostat/GetTemp")
.then(response => response.text())
.then(data => {
this.setState({ temp: data });
});
}
render () {
return (
<div>
<h1>Thermostat</h1>
<p>The temperature is:{this.state.temp}</p>
</div>
);
}
}
The problem I am having is that I want to display the current temperature of the Thermostat when the user visits the application. I am not sure how to create that new thermostat and display the temperature in my React code? I have looked at other Stack Overflow answers but am still finding it difficult to implement here (I'm very new to React and .NET). Can anyone help? Thank you :)
UPDATE
After receiving the following error InvalidOperationException: Unable to resolve service for type 'System.Int32' while attempting to activate 'ThermostatDotNet.Controllers.ThermostatController'. I managed to fix this by using an interface and implementing this:
[Route("api/[controller]")]
public class ThermostatController : Controller
{
private readonly ITemperature _temperature;
private int _Temperature { get; set; }
public ThermostatController(ITemperature temperature)
{
_temperature = temperature;
}
[HttpGet, Route("GetTemp")]
public int GetTemp()
{
return _Temperature;
}
}
First of all you need to return number from your controller like this.
Using return Ok();
[Route("api/[controller]")]
public class ThermostatController : Controller
{
public ThermostatController()
{
}
[HttpGet, Route("GetTemp")]
public int GetTemp()
{
return Ok(1);
}
}
Update: Then in your react use componentDidMount make sure you console.log(data) to see the data then use data.something to display data
componentDidMount() {
fetch("api/Thermostat/GetTemp")
.then(data => {
console.log(data);
this.setState({ temp: data });
});
}
You can read a document here

Lightning Web Component to display JSON String is not working

I have the following lightning web component to read a JSON string and display them in Contact record Details page. Please note that I am new to lighting web components and making a considerable amount of effort to learn.
MyComponent.html
<template>
<lightning-record-form
object-api-name={contactObject}
fields={myFields}
onsuccess={handleContactCreated} onload={handleContactInitialized} >
</lightning-record-form>
</template>
MyComponent.js
import { LightningElement, wire, track } from 'lwc';
import findDetails from
'#salesforce/apex/JSONDemoController.getContactWithRelatedDataById';
import CONTACT_OBJECT from '#salesforce/schema/Contact';
import NAME_FIELD from '#salesforce/schema/Contact.Name';
import TEST_FIELD from '#salesforce/schema/Contact.TestField__c';
import SPOUSE_FIELD from '#salesforce/apex/ResponseJSONWrapper.spouse';
import ADDRESS_FIELD from
'#salesforce/apex/ResponseJSONWrapper.mailingAddress';
export default class ContactCreator extends LightningElement {
contactObject = CONTACT_OBJECT;
myFields = [SPOUSE_FIELD,ADDRESS_FIELD];
#track contacts;
#track error;
handleContactCreated(){
// Run code when account is created.
}
handleContactInitialized(){
findDetails()
.then(result => {
var responseObj = JSON.parse(result.getReturnValue());
this.SPOUSE_FIELD = responseObj.spouse;
this.ADDRESS_FIELD = responseObj.mailingAddress;
})
.catch(error => {
this.error = error;
});
myFields = [SPOUSE_FIELD,ADDRESS_FIELD];
}
}
JSONDemoController.cls
public class JSONDemoController {
#AuraEnabled
public static String getContactWithRelatedDataById() {
String response = '';
ResponseJSONWrapper wrapper = new ResponseJSONWrapper();
wrapper.spouse = 'Test Spouse';
wrapper.mailingAddress = 'Test Address';
response = JSON.serialize(wrapper);
return response;
}
}
ResponseJSONWrapper.cls
public with sharing class ResponseJSONWrapper {
public String spouse;
public String contactRecordType;
public Date birthDate;
public String mobile;
public String mailingAddress;
public String otherAddress;
public String languages;
public String level;
public String Description;
}
But I don't get the values I have hard coded in the lightning component when it is rendered. Nothing is there it's empty.
Can someone help to point out where I am going wrong ?
Change this line:
var responseObj = JSON.parse(result.getReturnValue());
To:
var responseObj = JSON.parse(result);
getReturnValue() is for Aura components.
You don't actually need to serialize the wrapper in apex and then parse in the component explicitly, the framework does the job by itself!
public class JSONDemoController {
#AuraEnabled //change return type to ResponseJSONWrapper
public static ResponseJSONWrapper getContactWithRelatedDataById() {
String response = '';
ResponseJSONWrapper wrapper = new ResponseJSONWrapper();
wrapper.spouse = 'Test Spouse';
wrapper.mailingAddress = 'Test Address';
return wrapper; //return the wrapper itself
}
and in .js file
findDetails()
.then(result => {
var responseObj = result;
...
})
This way the code will be less cluttered with not-needed code :)

ERR_INCOMPLETE_CHUNKED_ENCODING on angularjs - rest service returns an infinite json file using Advanced REST Client but error in postman

I have a very strange problem. In angular (app built with ionic v1) I call some REST call built in java, but something goes wrong and chrome advise me with this error:
The code interesting is this, a REST service in angular js:
bankaccountsbyuser: function(_getbauser, _error){
var currentToken = _GetToken();
if(currentToken!=null){
var Headers = {
token: currentToken.tokenUser,
};
}
_timerTokenControl(currentToken, _error);
if (setupTime == null) {
console.log("token scaduto");
//modificare
//$window.location.href="login.html";
}
if (currentToken !== null) {
$http({
method : 'GET',
headers: Headers,
url : REST_URL+'bankaccount'
}).then(function successCallback(response) {
console.log(response)
_getbauser(response)
}, function errorCallback(response) {
console.log(response.statusText);
});
} else {
var alertPopup = $ionicPopup.alert({
title: 'Accesso negato!',
template: 'Devi essere un utente registrato, non sei loggato!'
});
console.log("NON SEI LOGGATO!!!");
}
},
debug:
How you can see, the get REST service returns an error, thus, let's see this REST service built in java:
package it.jack.fdd.services;
import java.util.List;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import it.jack.fdd.dao.FactoryDao;
import it.jack.fdd.dao.impl.BankAccountDaoImpl;
import it.jack.fdd.dao.interfaces.BankAccountDao;
import it.jack.fdd.domain.BankAccount;
import it.jack.fdd.domain.User;
import it.jack.fdd.dto.TokenUserDto;
import it.jack.fdd.dto.UserDto;
import it.jack.fdd.util.ConverterDTO;
#Path("/bankaccount")
public class BankAccountServices {
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<BankAccount> getBankAccountOfUser() {
BankAccountDao baDao = new BankAccountDaoImpl();
List<BankAccount> balist = baDao.getBAByUserId(1);
return balist;
}
I tryed to pass the number "1" in the method, just to simplify. The method is implemented below:
package it.jack.fdd.dao.impl;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import it.jack.fdd.dao.interfaces.BankAccountDao;
import it.jack.fdd.domain.BankAccount;
import it.jack.fdd.domain.Staff;
import it.jack.fdd.domain.User;
import it.jack.fdd.util.HibernateUtilLezione;
public class BankAccountDaoImpl extends BaseDaoImpl<BankAccount> implements BankAccountDao{
public List<BankAccount> getBAByUserId(int id) {
try{
Session session = HibernateUtilLezione.openSession();
Transaction tx = session.beginTransaction();
#SuppressWarnings("unchecked")
List<BankAccount> accounts = session.createQuery("from BankAccount b "
+ "where b.user= "+id).list();
tx.commit();
session.close();
return accounts;
}
catch(HibernateException e){
e.printStackTrace();
return null;
}
}
}
As you can see, the method ask for an id, and I put id 1 just to check, because in the database there is a field with that id. Trying in java, it returns me a list
[it.jack.fdd.domain.BankAccount#4f8d86e4]
And I checked also that the list has dimension 1 (thus, only one record, like in the database, only 1 record with that iduser)
Thus, trying to open this REST call using postman, the result is this:
The strange thing is that postman show me the same result to another REST call, that it worked before. But for this last REST call is not a problem, because strangely it works on my application, it doesn't work only in postman.
Thus, trying with Advanced REST Client I have a strange different result:
A strange, very big list that repeat every time the same field!! It is like a loop!
What happens? How I can solve?
Solved. The problem was in java's domain classes: when a domain class has a one-to-many relationship it's mandatory to put the tag #JsonIgnore to avoid these recurrent records in json file
Entity class:
package it.jack.fdd.domain;
// Generated 30-nov-2016 0.17.09 by Hibernate Tools 4.3.1.Final
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* BankAccount generated by hbm2java
*/
#Entity
#Table(name = "bank_account", catalog = "fdd_dbproducts")
public class BankAccount implements java.io.Serializable {
private Integer idbankAccount;
private User user;
private String iban;
private String pin;
private String society;
private Date expiration;
public BankAccount() {
}
public BankAccount(User user, String iban, String pin, String society) {
this.user = user;
this.iban = iban;
this.pin = pin;
this.society = society;
}
public BankAccount(User user, String iban, String pin, String society, Date expiration) {
this.user = user;
this.iban = iban;
this.pin = pin;
this.society = society;
this.expiration = expiration;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "idbank_account", unique = true, nullable = false)
public Integer getIdbankAccount() {
return this.idbankAccount;
}
public void setIdbankAccount(Integer idbankAccount) {
this.idbankAccount = idbankAccount;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "fkuser_baccount", nullable = false)
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
#Column(name = "iban", nullable = false, length = 45)
public String getIban() {
return this.iban;
}
public void setIban(String iban) {
this.iban = iban;
}
#Column(name = "pin", nullable = false, length = 45)
public String getPin() {
return this.pin;
}
public void setPin(String pin) {
this.pin = pin;
}
#Column(name = "society", nullable = false, length = 45)
public String getSociety() {
return this.society;
}
public void setSociety(String society) {
this.society = society;
}
#Temporal(TemporalType.DATE)
#Column(name = "expiration", length = 10)
public Date getExpiration() {
return this.expiration;
}
public void setExpiration(Date expiration) {
this.expiration = expiration;
}
}

Getting a value in application.properties file using javascript in spring boot

In my index.html page, a variable in the script is hard coded. I want to get it from application.properties file but have no idea how to. It would helpful if anyone could provide me a solution.
I have attached the example. Hope to help.
Application
#SpringBootApplication
public class Application {
public static void main(String... args) {
SpringApplication.run(Application.class);
}
}
PropertiesController
#RestController
public class PropertiesController {
#Autowired
private UIProperty uiProperty;
#RequestMapping("properties")
public UIProperty getProperties() {
return uiProperty;
}
}
UIProperty
#Component
#ConfigurationProperties(prefix = "ui.label")
public class UIProperty {
private String user;
private String password;
public void setUser(String user) {
this.user = user;
}
public String getUser() {
return user;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
}
application.properties
ui.label.user=user
ui.label.password=password
database.user=
database.password=
I'd create a RestController to expose ConfigurationProperties. But be sure to properly secure it as well as limit in its scope not to disclose confidential data like db access credentials.

Categories