【问题标题】:await is a reserved word on fetch requestawait 是获取请求的保留字
【发布时间】:2019-03-12 09:26:34
【问题描述】:

我正在尝试发出 fetch 请求但无法正常工作。这是我的工作

客户端:

this.state= {
   from: "from@email.com",
   to: "to@email.com",
   subject: "mainSubject",
   message: "main message",
}

handeSendRequest(){

   await fetch('/api/sendIt', {method:'post', headers: {'Content-type' : 'application/json' }}, body: JSON.stringify(this.state)){

    }

}
render(){
  return(
    <Button onClick={this.handeSendRequest} > Send it </Button>
   )

 }

电子邮件-util.js

const mailgun = require('mailgun-js')(mailGunConfig);


var data = {
  from: req.body.from,
  to: req.body.to,
  subject: req.body.subject,
  text: req,body.text
}

mailgun.message().send(data,function(error, body){
  if(error){
    console.log(error)
  } else {
    console.log(body)
  }

}  )

server.js

const app = express();

const emailUtil = require('./email-util');

app.use('/api/sendIt', emailUtil);

我是前端和后端工作的新手,并且一直在处理这个问题。我得到的错误是await is a reserved word

【问题讨论】:

  • 你的 email-util.js 需要是一个模块化的路由处理程序。检查底部hereexpress.Router 部分。您需要 router.post('/', ...),因为您要发送 POST 请求。 (并暂时删除await,因为无论如何您在发送请求后什么都不做)
  • 您必须将您的函数标记为async 才能使用await。尾随花括号也是语法错误。

标签: javascript node.js reactjs


【解决方案1】:

可能只是handeSendRequest需要声明为async函数:

async handeSendRequest(){
  await fetch('/api/sendIt', {method:'post', headers: {'Content-type' : 'application/json' }}, body: JSON.stringify(this.state))
}

【讨论】:

    【解决方案2】:

    await 只能在异步函数中调用,请尝试以下操作。

    async handeSendRequest() {
      await fetch...
    }
    

    【讨论】:

      【解决方案3】:

      await 仅适用于异步函数。您可以将获取请求更改为以下内容:

          async handeSendRequest(){
             let response= await fetch('/api/sendIt', {method:'post', headers: {'Content-type' : 'application/json' }}, body: JSON.stringify(this.state));
             let result=await response.json();
              console.log(result)
      
          }
      

      【讨论】:

        猜你喜欢
        • 2017-05-24
        • 2019-08-03
        • 1970-01-01
        • 1970-01-01
        • 2019-03-05
        • 2019-03-28
        • 2016-11-25
        • 2017-12-08
        • 2017-07-07
        相关资源
        最近更新 更多