如何使用fetch在react/javascript中发送curl请求?

问题描述 投票:0回答:1

我想提出一个请求..这是curl请求

curl --location --request POST '2.2.2.22:343/sudun/cars' \
--header 'Authorization: Bearer sdswmaiqwasae*********' \
--header 'Content-Type: application/json' \
--data-raw '{
    "user": "sdsffwefwefwssdsds",
    "numberofunits": 4,
    "price": 0
}'

这就是我正在做的事情。

const url = "2.2.2.22:343/sudun/cars";

const options = {
  headers: {
    "Authorization": "Bearer sdswmaiqwasae*********",
    "Content-Type": "application/json"
  }
};

fetch(url, options)
  .then( res => res.json() )
  .then( data => console.log(data) );

它不起作用...我知道我没有添加 --data-raw 部分...我不知道该怎么做..

javascript reactjs curl fetch-api
1个回答
2
投票

如果您使用 fetch,可以这样尝试。

var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer sdswmaiqwasae*********");
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  "user": "sdsffwefwefwssdsds",
  "numberofunits": 4,
  "price": 0
});

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("2.2.2.22:343/sudun/cars", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));
© www.soinside.com 2019 - 2024. All rights reserved.