获取 post 正文数据无效参数为空

Fetch post with body data not working params empty

我正在尝试重写我的 ajax 调用以获取:

Ajax:

  $.post({
    context: this,
    url: "/api/v1/users",
    data: { 
      user: 
        {
          email: email,
          password: password
        } 
    }
  }).done((user) => {
  }).fail((error) => {
  })

获取:

  fetch('/api/v1/users', {  
  method: 'POST',
  headers: {
    "Content-Type": "application/json"
  },      
    body: { 
    "user" : 
      {
        "email" : email,
        "password" : password
      } 
  }
  })
  .then(res => {  
    if (res.status !== 200) { {
        console.log("error")
      })          
    } else {
      res.json().then(data => {
        console.log(data)
      })
    }
  })

我从我的服务器收到错误空参数 ~ 错误请求。

我也找到了这种方法,但在下面的代码中出现错误:意外令牌。

  var payload = { 
    "user" : 
      {
        "email" : email,
        "password" : password
      } 
  };

  var data = new FormData();
  data.append( "json", JSON.stringify( payload ) );

  fetch('/api/v1/users', {  
  method: 'POST',
  headers: {
    "Content-Type": "application/json"
  },      
    body: data
  })

如何重写 ajax 获取请求?

你应该试试这个:

fetch('/api/v1/users', {
    method: 'post',
    body: JSON.stringify({"user":{
        "email": email,
        "password": password
    }}),
});

fetch API

在 github 上关注了这个主题:https://github.com/matthew-andrews/isomorphic-fetch/issues/34

我的问题的解决方案是使用 JSON.stringify 函数并将 Content-Type header 设置为 application/json。不太清楚为什么我的问题中的第二次尝试没有奏效。

fetch('/api/v1/users', {  
    method: 'post',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({ "user": {
      "email" : email,
      "password" : password
    }}),
})

官方 MDN 文档:

var myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/json');

fetch('/contact-form', {
    method: 'POST',
    headers: myHeaders,
    mode: 'cors',
    cache: 'default',
    body: JSON.stringify(fields)
}).then(() => {
    dispatch(contactFormSubmitSuccess());
});

在发送 body 时以这种方式工作,因为 json 失败。

        var formData = new FormData();
        formData.append('key1', 'value1');
        formData.append('key1', 'value2');

        fetch('url', {
            method: 'post',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'multipart/form-data'
            },
            body: formData
        }`)`

编辑:就我而言,服务器仅通过表单数据提交识别内容。代码未编写为将请求正文读取为 json。因此,您的服务器端代码也有可能存在问题。

headers: {'Content-Type': 'application/json'}

已回答

如果您使用 Express 服务器来处理请求,请确保在这一行中添加:

app.use(express.json({limit:'1mb'}))

TL;DR 如果没有 mode: 'cors',您的 JSON body 将无法通过。

我为此纠结了一会儿。 cors 是问题所在。假设您正在执行从一个域到另一个域的请求(即从 localhost:8080localhost:3000),您需要在获取设置和接收域中包含 mode: 'cors' (localhost:3000)需要允许来自发送域 (localhost:8080) 的请求。

所以上面代码中的描述:

请求从 localhost:8080localhost:3000

fetch('http://localhost:3000/users/sign_in', {
      method: 'POST',
      mode: 'cors', // this cannot be 'no-cors'
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        "user": {
          "email": `${this.state.userEmail}`,
          "password": `${this.state.userPass}`
        }
      }),
    })

然后确保您的接收域 localhost:3000 允许来自 localhost:8080 的 CORS。

尝试将 (body-parser) 放在 app.js / server.js 的顶部:

app.use(bodyParser.json());

唯一对我有用的是把

app.use(express.json())

在我的主服务器文件中。