首页 > 解决方案 > 将 cURL 命令转换为 Axios

问题描述

我正在尝试向记录为 cURL 命令的 API 发出发布请求。给出的 cURL 命令是:

curl -H m-token:"sfg999666t673t7t82" -H "Content-Type: application/json" -H "accept: application/json" -d '{"id":"3970a1b0-6e27-448a-adfc-0083db15b2fb", "tokens":{"name":"Hi","email":"Hello@m.com"}, "recipient":"james.sampleton@sample.com"}' -X POST "https://example.com/mas/api/v1/mail/transactional"

我使用的 axios 请求是 axios.post('https://example.com/mas/api/v1/mail/transactional', { id: '3970a1b0-6e27-448a-adfc-0083db15b2fb', tokens: { name: 'Hi', email: 'Hello@m.com' }, recipient: 'james.sampleton@sample.com"' }, { headers: { Accept: "application/json", "Content-Type": "application/json", "m-Token": "sfg999666t673t7t82" } });

此请求引发 400 错误。我应该在 axios 请求中进行任何更改吗?

标签: reactjscurlaxios

解决方案


var axios = require('axios');
var data = JSON.stringify({"id":"3970a1b0-6e27-448a-adfc-0083db15b2fb","tokens":{"name":"Hi","email":"Hello@m.com"},"recipient":"james.sampleton@sample.com"});

var config = {
  method: 'post',
  url: 'https://example.com/mas/api/v1/mail/transactional',
  headers: { 
    'm-token': 'sfg999666t673t7t82', 
    'Content-Type': 'application/json', 
    'accept': 'application/json'
  },
  data : data
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});

推荐阅读