【问题标题】:Display Json in console on page when the button is clicked?单击按钮时在页面上的控制台中显示 Json?
【发布时间】:2021-08-05 13:36:11
【问题描述】:

我目前正在从我的后端服务器获取 JSON 并将其显示在我的控制台中。当出于测试目的单击提交按钮时,我试图在网页上以原始形式在控制台中显示 JSON。有没有简单的方法来解决这个问题?我目前只是更改窗口,但控制台中的数据甚至没有显示在邮递员中。

也许我可以在表单下方的框中显示数据?

请在下面查看我的 React 代码

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>
    )
  }
}

请看下面我的服务器端

@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());

    }
}

【问题讨论】:

    标签: javascript json reactjs spring-boot react-native


    【解决方案1】:

    如果您只是想测试,那么使用控制台似乎就足够了,但如果您想将它存储在页面上,我会创建一个有状态的变量,例如 rawResponse。当您从 API 取回数据时,您可以更新该变量以包含 json(您可能需要先将 json 字符串化以将其转换为字符串)。

    然后,您的页面中有一些条件渲染来显示该 json,如下所示:

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

    这只是将rawResponse 的内容呈现在“pre”标签中,该标签应该像代码或其他东西一样格式化它。如果您不熟悉该行代码的作用,可以查找“react 中的条件渲染”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-13
      • 1970-01-01
      • 1970-01-01
      • 2013-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多