【问题标题】:Invalid Json in Body on Rest ApiRest Api 上的正文中的无效 Json
【发布时间】:2019-01-28 09:14:41
【问题描述】:

我正在使用 Rest Api 和 Mongo DB 使用 Angular 构建一个 CRUD 应用程序。 在我的应用程序中,我向 Rest Api 发送了一个 Post 对象,但请求的正文中有一个 Invalid Json:

{
 '{"_id":"","user":"Maius_XX","content":"asdasfd","lits":13,"shits":2,"comments":{},"timestamp":"Sun Jan 27 2019 21:07:11 GMT 0100 (Mitteleuropäische Normalzeit)"}': ''
}

我尝试解析body或发送其他信息,但仍然有无效的Json。

我的 Angular 代码:

createNewPosts(post: Post) {
    const httpOptions = {
    headers: new HttpHeaders({
        'Content-Type':  'application/x-www-form-urlencoded; charset=UTF-8'
    })
};

this._http.post<Post>(this.urlPosts, post, httpOptions)
    .subscribe(
        res => {
            console.log(res);
        },
        err => {
            console.log("Error occured " + err );
        }
    );

我的后台:

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

const product = new Product({
    _id: new mongoose.Types.ObjectId(),
    user: req.body.user,
    content: req.body.content,
    lits: req.body.lits,
    shits: req.body.shits,
    comments: req.body.comments,
    timestamp: req.body.timestamp
});
console.log(req.body);
product.save().then(result => {
        console.log(result);
        res.status(201).json({
            message: "Handling Post",
            createdProduct: result
        })
    })
    .catch(err => {
        console.log(err);
        res.status(500).json({
            error: err
        });
    });
});  

和:

app.use(morgan('dev')); 
app.use(bodyParser.json());

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Alllow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
    if (req.method === 'OPTIONS') {
        res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
        return res.status(200).json({});
    }
    next();
});

app.use('/products', productRoutes);

app.use((req, res, next) => {
    const error = new Error('Not found');
    error.status = 404;
    next(error);
})

app.use((error, req, res, next) => {
    res.status(error.status || 500);
    res.json({
        error: {
            message: error.message
        }
    })
})

【问题讨论】:

    标签: node.js angular rest api


    【解决方案1】:

    Content-Type 更改为:

    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    

    收件人:

    'Content-Type': 'application/json; charset=UTF-8'
    

    【讨论】:

    • @MaG。 Cors 与您的前端无关。您需要在后端对其进行配置。你能分享一下错误吗?
    • 是的 cors 需要在后端进行配置,但是使用 application/x-www-form-urlencoded 它可以工作......这就是错误:访问 XMLHttpRequest at 'localhost:3000/products' from origin' localhost:4200' 已被 CORS 策略阻止:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段内容类型。
    • @MaG。如果要使用 application/x-www-form-urlencoded 发送数据,则需要序列化数据。如果您想使用 json 发送它,请尝试允许任何来源、任何标头和任何方法,在开发时这应该不是问题,稍后在生产中尝试匹配所有这些设置
    猜你喜欢
    • 2018-10-11
    • 2019-12-14
    • 2016-03-29
    • 2014-06-20
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多