获取正文数据无效的帖子,参数为空

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

我正在尝试重写我的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)
      })
    }
  })

我收到错误empty params ~ 来自我的服务器的错误请求。

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

  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请求来获取?

ajax fetch
9个回答
66
投票

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

我的问题的解决方案是使用 JSON.stringify 函数并将 Content-Type 标头设置为 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());
});

21
投票

TL;DR 没有

mode: 'cors'
,您的 JSON 正文将无法通过。

我为此纠结了一会儿。

cors
就是问题所在。假设您正在执行从一个域到另一个域的请求(即从
localhost:8080
localhost:3000
),您需要在获取设置中包含
mode: 'cors'
并且您的接收域 (
localhost:3000
) 需要允许来自发送域的请求(
localhost:8080
).

所以上面代码中的描述:

localhost:8080
localhost: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。


14
投票
headers: {'Content-Type': 'application/json'}

已经回答了


9
投票

发送

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。因此,您的服务器端代码也可能存在问题。


8
投票

如果您使用 Express 服务器来处理请求,请确保添加以下行:

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

5
投票

唯一对我有用的就是放

app.use(express.json())

在我的主服务器文件中。


2
投票

你应该尝试这个:

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

获取API


1
投票

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

app.use(bodyParser.json());

0
投票

问题是 fetch 不适用于 no-cors。 所以你应该像这样在 cors 上设置模式:

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

常量参数 = { 键:值,

};

等待获取(“url_here”, { 方法:“POST”, 标题:我的标题, 模式:“cors”, 缓存:“默认”, 正文:JSON.stringify(参数), } )

© www.soinside.com 2019 - 2024. All rights reserved.