这是我使用 axios 在 post 中发送准备好的 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
});
但我总是收到以下错误 (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.
答案 0 :(得分:1)
catch
响应代码为非 20X 时的错误
const options = {
headers: {'content-type': 'application/json'}
};
axios.post(
'/login',
{
firstName: 'Finn',
lastName: 'Williams'
},
options
).catch((error) => {
console.log(error)
});
答案 1 :(得分:0)
415 表示不受支持的媒体类型。 https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/415
确保 API 端点支持 json 请求。祝你好运!