1

如何将此 curl 请求转换为 javascript 中的 ajax 调用?(原始 js 或任何库中的答案都可以)

卷曲:

curl -H "Content-Type: application/json" -d '{"foo":0, "bar": 0, "baz":"test"}' -X GET http://localhost:8080/public/v1/state/HelloWorld

我在 ajax 调用中尝试的 URL(它给出了 404 错误):

GET http://192.168.56.101:8080/public/v1/state/HelloWorld?foo=0&bar=0&baz=test

代码

return axios.get(switchDomain + '/public/v1/state/HelloWorld', {
    params: {
      foo: 0,
      bar: 0,
      baz: "BER",
    }
  })
  .then(function(response){
    console.log('perf response', response);
  });
4

1 回答 1

3

无论您的选择如何,似乎-d都会将您的 CURL 请求变成:POST-X

var req = new  XMLHttpRequest();
req.open( "POST", "http://localhost:8080/public/v1/state/HelloWorld", true);
req.send("foo=0&bar=0&baz=test");

最终,您可能需要在 之后req.open和之前添加内容类型标头req.send

req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

或者如您的问题中所发布,您可能希望将其作为 JSON 发送

var req = new  XMLHttpRequest();
req.open( "POST", "http://localhost:8080/public/v1/state/HelloWorld", true);
req.setRequestHeader("Content-Type", "application/json");
req.send(JSON.stringify({
    foo: 0,
    bar: 0,
    baz: "test"
}));
于 2016-08-29T00:41:55.727 回答