Display Json in console on page when the button is clicked?

Viewed 80

I am currently getting JSON from my back end server and displaying it in my console. I am trying to display the JSON in the console in raw form on a webpage when the submit button is clicked for testing purposes. Is there an easy way to go about this? I am currently just changing window, but the data in the console isn't even showing up in postman.

Maybe I can display the data in a box underneath the form?

Please see my React code below

import React, {Component} from 'react';
import {Card,Form,ButtonGroup,Button,Col} from 'react-bootstrap';
import axios from "axios";

export default class MovieList extends Component {

constructor(props){
super(props);
var config = { headers: {'Access-Control-Allow-Origin': '*'}};
this.state = this.startState;
}
startState = {id: ""};


  handleSubmit = event => {
    event.preventDefault();
    const id = {
      id: this.state.id
    }

    axios.get("http://localhost:8082/movies/" + this.state.id, this.config)
      .then(res => {
        window.location = "/retrieve" //This line of code will redirect you once the submission is succeed
        console.log(res);
        console.log(res.data);
        JSON.stringify(res)
        JSON.stringify(res.data)

      })
      .catch((error) => {
                console.error("Error has been caught: " + error);
                console.log(error);
                console.trace();
            });

  }
  handleChange = event => {
    this.setState({
      id: event.target.value
    });
  }

  render() {
  const {id} = this.state
    return (
    <Card className = {"border border-dark bg-dark text-white"}>
      <Card.Header> Get Json </Card.Header>
      <Form>
      <Card.Body>
      <Form.Group as = {Col}>
      <Form.Label> Customer ID </Form.Label>
      <Form.Control
      type = "test"
      placeholder = "Enter ID"
      value={id}
      onChange={this.handleChange}
       />
      <Form.Text className = "text-muted" >
      Press Get Json to receive JSON Data
      </Form.Text>
      </Form.Group >
      </Card.Body>
      <Card.Footer style = {{"textAlign": "right"}}>
      <Button onClick = {this.handleSubmit}
      size = "m"
      variant = "success"
      type = "submit" >
      Get Json
      </Button>
      </Card.Footer>
      </Form>
      </Card>
    )
  }
}

Please see my server side below

@CrossOrigin(origins = "http://localhost:3000", methods = {RequestMethod.OPTIONS, RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE}, allowedHeaders = "*", allowCredentials = "true")
@RestController
@RequestMapping("/movies")
public class MovieResource {

    @Value("${api.key}")
    private String apiKey;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/{movieId}")
    public Movie getMovieInfo(@PathVariable("movieId") String movieId) {
        MovieSummary movieSummary = restTemplate.getForObject("https://api.themoviedb.org/3/movie/" + movieId + "?api_key=" +  apiKey, MovieSummary.class);
        return new Movie(movieId, movieSummary.getTitle(), movieSummary.getOverview());

    }
}
1 Answers

If you're just trying to test then using the console seems like it would be good enough but if you want to store it on the page I'd create a stateful variable like rawResponse. When you get the data back from the API you can update that variable to contain the json (you probably need to stringify the json first to turn it into a string).

Then you have some conditional rendering in your page to display that json like this:

{rawResponse != "" && <pre>{rawResponse}</pre>}

that simply renders the contents of rawResponse in a "pre" tag which should format it like it's code or something. If you're unfamiliar with what that line of code does you can look up "conditional rendering in react".

Related