【问题标题】:Creating JSON object based on JSON file基于 JSON 文件创建 JSON 对象
【发布时间】:2019-01-26 23:02:46
【问题描述】:

我在发送时无法检索有关电影的信息 GET 请求 omdbapi.com。

这是处理对我的数据库的POST 请求的代码:

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

const Movie = require('../models/movie');

router.post('/', (req, res, next) => {

    var temp;
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function(){
        if (this.readyState == 4 && this.status == 200) {
            temp = JSON.parse(this.responseText);
        }
    };
    xhr.open("GET", "http://www.omdbapi.com/?t=" + req.body.title + "&apikey=xyz", true);
    xhr.send();

    const movie = new Movie({
            _id: new mongoose.Types.ObjectId(),
            title: req.body.title,
            movieInfo: temp,
            comment: req.body.comment
    });

    movie
    .save()
    .then(result => {
        console.log(result);
        res.status(201).json({
            message: 'Created movie succesfully',
            createdMovie: {
                _id: movie._id,
                title: movie.title,
                movieInfo: movie.movieInfo,
                comment: movie.comment
            }
        });
    })
    .catch(err => {
        console.log(err);
        res.status(500).json({
            error : err
        });
    });
});

module.exports = router;

我的问题是,除了movieInfo之外的所有东西都通过了,我想成为一个嵌套的JSON对象,比如

createdMovie{
 ...
 movieInfo: {
  Title: a,
  Actors: b,
  ...
  ...
 }
 ...
}

这是我正在研究的猫鼬模式

const mongoose = require('mongoose');

const movieSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    title: String,
    movieInfo: String,
    comment: String
});

module.exports = mongoose.model('Movie', movieSchema);

当我POST 电影时,这就是我在测试时得到的(我使用 Postman 进行测试)。

{
    "message": "Created movie succesfully",
    "createdMovie": {
        "_id": "5b7b0da48f5fb04e3c0f740b",
        "title": "Goodfellas",
        "comment": "some comment"
    }
}

所以我错过了movieInfo,我不知道是因为它甚至没有到达对象,因为我以错误的方式传递它,或者它只是没有显示。尝试了不同的猫鼬类型,例如StringArrayMixed,但都没有成功。

如果请求成功,你得到的 JSON 看起来像这样

{
    "Title":"Goodfellas",
    "Year":"1990",
    "Rated":"R",
    "Released":"21 Sep 1990",
    "Runtime":"146 min",
    "Genre":"Crime, Drama",
    "Director":"Martin Scorsese",
    "Writer":"Nicholas Pileggi (book), Nicholas Pileggi (screenplay), Martin Scorsese (screenplay)",
    "Actors":"Robert De Niro, Ray Liotta, Joe Pesci, Lorraine Bracco",
    "Plot":"The story of Henry Hill and his life in the mob, covering his relationship with his wife Karen Hill and his mob partners Jimmy Conway and Tommy DeVito in the Italian-American crime syndicate.","Language":"English, Italian","Country":"USA","Awards":"Won 1 Oscar. Another 43 wins & 37 nominations.",
    "Poster":"https://m.media-amazon.com/images/M/MV5BY2NkZjEzMDgtN2RjYy00YzM1LWI4ZmQtMjIwYjFjNmI3ZGEwXkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_SX300.jpg",
    "Ratings":[{"Source":"Internet Movie Database","Value":"8.7/10"},{"Source":"Rotten Tomatoes","Value":"96%"},{"Source":"Metacritic","Value":"89/100"}],
    "Metascore":"89",
    "imdbRating":"8.7",
    "imdbVotes":"855,144",
    "imdbID":"tt0099685",
    "Type":"movie",
    "DVD":"26 Mar 1997",
    "BoxOffice":"N/A",
    "Production":"Warner Bros.",
    "Website":"N/A",
    "Response":"True"
}

我想把它放在movieInfo 下,整个事情。如何实现?

【问题讨论】:

  • 在创建movie 对象时,您将movieInfo 设置为temp,我没有看到它已初始化。尝试初始化为有效值,看看是否能解决问题。

标签: javascript json node.js mongodb mongoose


【解决方案1】:

请求是否使用 Content-Type - application/json 发送?

【讨论】:

    【解决方案2】:

    将movieInfo数据类型更改为Object。

    const movieSchema = mongoose.Schema({
        _id: mongoose.Schema.Types.ObjectId,
        title: String,
        movieInfo: Object,
        comment: String
    });
    

    【讨论】:

    • 它已经是一个对象了,但我只是测试了它,似乎我的代码首先创建了一个带有空temp的JSON对象movieInfo,然后从omdbapi.com得到答案并通过JSON.parse(this.responseText)temp。如何让它等待响应,将其传递给temp,然后创建movieInfo = temp
    • 使用异步函数
    【解决方案3】:

    解决方案:

    所有东西都必须移到xhr.onreadystatechange 中,因为如果没有,那么当我创建一个Movie 对象时,omdbapi.com 的答案仍然没有到达。

    xhr.onreadystatechange = function(){
                    if(this.readyState == 4 && this.status == 200){
                        *your code here*
                    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-30
      • 2022-09-29
      • 2015-09-30
      • 1970-01-01
      • 1970-01-01
      • 2013-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多