【问题标题】:Axios not POSTing arrayAxios 不发布数组
【发布时间】:2021-12-14 12:35:03
【问题描述】:

我有一个向我的自定义 Flask API 发送数据的 React 应用。

const params = {
            id: this.props.user.uid,
            title: movie.title,
            movie_id: parseInt(movie.id, 10),
            photo: "https://image.tmdb.org/t/p/w500/" + movie.backdrop_path,
            year: parseInt(movie.release_date.split("-")[0], 10),
            rating: parseInt(parseFloat(movie.vote_average) * 10, 10),
            overview: movie.overview,
            genres: genres
        };

当我打印出params.genres 时,它会显示类似["Fantasy", "Comedy"] 的内容。 但是当我发布它时: axios.post("http://localhost:5000/user", params).then((data) => { 有效载荷是: {"id":"id","title":"The Watch","movie_id":80035,"photo":"urltoimage","year":2012,"rating":55,"overview":"overview","genres":[]}

所有值都是正确的,除了流派。在我的后端它也是这样说的。 怎么了?

我的全部功能:

addMovie(movie) {
        //get more data from tmdb
        var genres = [];
        axios
            .get(
                "https://api.themoviedb.org/3/movie/" +
                    parseInt(movie.id, 10),
                {
                    params: {
                        api_key: "dontsteelmytmdbkey;)",
                    },
                }
            )
            .then((req) => {
                for (let i = 0; i < req.data.genres.length; i++){
                    genres.push(req.data.genres[i].name);
                }
            });
        console.log(genres);
        const params = {
            id: this.props.user.uid,
            title: movie.title,
            movie_id: parseInt(movie.id, 10),
            photo: "https://image.tmdb.org/t/p/w500/" + movie.backdrop_path,
            year: parseInt(movie.release_date.split("-")[0], 10),
            rating: parseInt(parseFloat(movie.vote_average) * 10, 10),
            overview: movie.overview,
            genres: genres
        };
        console.log(params.genres);
        axios.post("http://localhost:5000/user", JSON.stringify(params)).then((data) => {
            if (data.data.code === 112) {
                // success alert
                console.log("success alert");
                // remove movie from list
                let newMovies = this.state.movies;
                for (let i = 0; i < newMovies.length; i++) {
                    if (newMovies[i].id === movie.id) {
                        newMovies.splice(i, 1);
                    }
                }
                this.setState({ movies: newMovies });
            } else {
                console.log("Backend error");
                console.log(
                    "Error: " + data.data.code + " - " + data.data.errno
                );
                this.setState({
                    showAlert: true,
                    alertSeverity: "error",
                    alertText: this.state.alertServerError,
                });
            }
        });

        // dont redirect
        //this.props.history.push("/");
    }

【问题讨论】:

  • 你能分享你的整个代码,包括流派数组,然后我可以看看吗?
  • 我上传了我的整个添加函数
  • console.log(genres)console.log(params.genres) 都返回了一系列类型,正如我之前所说的

标签: javascript arrays reactjs json axios


【解决方案1】:

这些 axios 调用目前都是异步的,它们不会等待对方解决。 尝试像这样修改您的代码以等待第一个调用被解析,然后循环遍历流派。

// add async to function definition 
async function addMovie(movie) {
  // get more data from tmdb
  const genres = [];
  try {
    const response = await axios.get('https://api.themoviedb.org/3/movie/' + parseInt(movie.id, 10), {
      params: {
        api_key: 'dontsteelmytmdbkey;)',
      },
    });

    for (let i = 0; i < response.data.genres.length; i++) {
      genres.push(response.data.genres[i].name);
    }
  } catch (error) {
    console.error(error);
  }
  console.log(genres);
  const params = {
    id: this.props.user.uid,
    title: movie.title,
    movie_id: parseInt(movie.id, 10),
    photo: 'https://image.tmdb.org/t/p/w500/' + movie.backdrop_path,
    year: parseInt(movie.release_date.split('-')[0], 10),
    rating: parseInt(parseFloat(movie.vote_average) * 10, 10),
    overview: movie.overview,
    genres: genres,
  };
  console.log(params.genres);
  axios.post('http://localhost:5000/user', JSON.stringify(params)).then((data) => {
    if (data.data.code === 112) {
      // success alert
      console.log('success alert');
      // remove movie from list
      let newMovies = this.state.movies;
      for (let i = 0; i < newMovies.length; i++) {
        if (newMovies[i].id === movie.id) {
          newMovies.splice(i, 1);
        }
      }
      this.setState({ movies: newMovies });
    } else {
      console.log('Backend error');
      console.log('Error: ' + data.data.code + ' - ' + data.data.errno);
      this.setState({
        showAlert: true,
        alertSeverity: 'error',
        alertText: this.state.alertServerError,
      });
    }
  });

  // dont redirect
  // this.props.history.push("/");
}

【讨论】:

  • 感谢您的尝试声明。
【解决方案2】:
var genres = [];
        const res = await axios
            .get(
                "https://api.themoviedb.org/3/movie/" +
                    parseInt(movie.id, 10),
                {
                    params: {
                        api_key: "dontsteelmytmdbkey;)",
                    },
                }
            )
            
            for (let i = 0; i < res.data.genres.length; i++){
                    genres.push(res.data.genres[i].name);
            }

让你的 addMovie 函数异步,在 addMovie 函数之前使用 async 关键字。

为什么需要这个?因为你必须等到 axios 响应解决。

为了更好地理解,您可以阅读有关 Async Await 的更多信息

【讨论】:

    【解决方案3】:

    它不会等待执行 API 调用,您应该使用 async 和 await。我在下面的代码中添加了:

    addMovie(movie) async {
        //get more data from tmdb
        var genres = [];
        await axios
            .get(
                "https://api.themoviedb.org/3/movie/" +
                    parseInt(movie.id, 10),
                {
                    params: {
                        api_key: "dontsteelmytmdbkey;)",
                    },
                }
            )
            .then((req) => {
                for (let i = 0; i < req.data.genres.length; i++){
                    genres.push(req.data.genres[i].name);
                }
            });
        console.log(genres);
        const params = {
    

    【讨论】:

    • 这不是等待请求被解析的正确方法异步应该在函数关键字回调链接之前,并且等待不能以这种方式工作我猜这个答案不应该被标记为接受一个
    • 我没有权限编辑或评论您的答案,但如果请求未处理或由于服务器问题,您的代码最终会破坏代码。您需要在 try catch 块中添加 api 调用。
    猜你喜欢
    • 2023-03-15
    • 2018-07-18
    • 2020-11-26
    • 2020-12-15
    • 1970-01-01
    • 2017-09-14
    • 2021-11-23
    • 2019-04-03
    • 2020-04-03
    相关资源
    最近更新 更多