繁体   English   中英

单击按钮时在页面上的控制台中显示 Json?

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

我目前正在从我的后端服务器获取 JSON 并将其显示在我的控制台中。 当单击提交按钮进行测试时,我试图在网页上以原始形式在控制台中显示 JSON。 有没有一种简单的方法来 go 关于这个? 我目前只是更改 window,但控制台中的数据甚至没有显示在 postman 中。

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

请在下面查看我的 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());

    }
}

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM