json React Js:未捕获(在承诺中)语法错误:[副本]

5jvtdoz2  于 2023-01-14  发布在  React
关注(0)|答案(2)|浏览(88)
    • 此问题在此处已有答案**:

POST Request with Fetch API?(7个答案)
4天前关闭。
我正在reactjs中尝试通过fetch进行POST请求。我查看了一些文档,但错误没有解决。有人能帮我吗?
下面是我的reactjs代码:

handleSubmit(e) {
       e.preventDefault();
       var self = this;
    
       const payload = {
       id: 111,
       studentName: 'param',
       age: 24,
       emailId: 2
    };
    fetch({
       method: 'POST',
       url: 'http://localhost:8083/students',
       body: payload,
       headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
     })
       .then(function(response) {
           return response.json()
         }).then(function(body) {
           console.log(body);
         });
     }
    
  }

如果有人熟悉reactjs,就举一个简单的例子来说明如何调用post request,可以使用fetch,也可以使用axios

ehxuflar

ehxuflar1#

这是一个例子。

fetch('http://myAPiURL.io/login',{
    method:'POST',
    headers:{
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    },
    body:JSON.stringify({
    email: userName,
    password: password
  })
  }).then(function (response) {

    //Check if response is 200(OK) 
    if(response.ok) {
      alert("welcome ");
    }
    //if not throw an error to be handled in catch block
    throw new Error(response);
  })
  .catch(function (error) {
    //Handle error
    console.log(error);
  });

for more info on how to use `fetch` https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
6psbrbz9

6psbrbz92#

我刚才回答了一个类似的问题。here
React最棒的地方在于它只是Javascript。
因此,所有您需要的是一些做POST做您的服务器!
您可以使用本机fetch函数或axios之类的完整库
使用两者的示例如下:

// Using ES7 async/await
const post_data = { firstname: 'blabla', etc....};
const res = await fetch('localhost:3000/post_url', { method: 'POST', body: post_data });
const json = await res.json();
// Using normal promises
const post_data = { firstname: 'blabla', etc....};
fetch('localhost:3000/post_url', { method: 'POST', body: post_data })
.then(function (res) { return res.json(); })
.then(function (json) { console.log(json); };
// AXIOS example straight from their Github
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

相关问题