简体   繁体   English

将 json 邮寄到服务器节点

[英]send json in post to a server node

This is the code I use to send a ready json in post using axios.这是我使用 axios 发送准备好的 json 的代码。

const axios = require("axios");

const jsonObj = {
    serial: '090982037439', //string
    sensor_type: 'ciccio bello', //string

    value_registered: {
        value: 30, //valore
        unit_of_measure: 'celsius' ///string
    },

    value_registered_at: '29-04-2021' ///string 

};

const json = JSON.stringify(jsonObj);

axios({
    method: 'post',
    url: 'http://localhost:3000/api/post',
    data: json
});

But I always get the following error (415) back.但我总是得到以下错误(415)。

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise 
rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:11188) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

415 Unsupported Media Type415 不支持的媒体类型

  1. Looks like axios don't need to stringify data (or that is optional)? 看起来axios 不需要对数据进行字符串化(或者这是可选的)?
  2. Try to set MIME type尝试设置 MIME 类型
  3. 415 Response code means that axios at least sending data. 415响应码表示axios至少发送数据。 So check problem at backend所以在后端检查问题
  4. catch error when response code is non-20X当响应码不是 20X 时catch错误

const options = {
  headers: {'content-type': 'application/json'}
};

axios.post(
  '/login',
  {
    firstName: 'Finn',
    lastName: 'Williams'
  },
  options
).catch((error) => {
  console.log(error)
});

415 means unsupported media type. 415 表示不支持的媒体类型。https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/415https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/415

Make sure that the API endpoint supports json request.确保 API 端点支持 json 请求。 Good luck!祝你好运!

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

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