【问题标题】:Failed to fetch - Heroku获取失败 - Heroku
【发布时间】:2021-11-17 04:40:34
【问题描述】:

我将 Node JS Express 用于后端,将纯 HTML 用于前端。单击按钮时,我正在尝试通过 Node JS 将表单数据发送到 MongoDB。

客户端 [HTML]

<a href="javascript:void(0);" onclick="sendData();" id="get-marker-value" class="btn pxp-hero-contact-form-btn">Get Market Value</a>

<script type="text/javascript">
            function sendData(event){
                let name = document.getElementById("name").value;
                let email = document.getElementById("email").value;
                let phone = document.getElementById("phone").value;
                let address = document.getElementById("address").value;

                if(name != '' || email != '' || phone != '' || address != ''){
                    let formData = JSON.stringify({
                        name: name,
                        phone: phone,
                        email: email,
                        address: address
                    });
                    let url="<SERVER_URL>/listing/add_listing";
                    
                    fetch(url, {
                        method: 'post',
                        body: formData,
                        headers:{"Content-Type" : "application/json"}
                    }).then(response => response.json())
                    .then( (result) => {
                        console.log('success:', result);
                        $('#get-marker-value').addClass('hide');
                        $('#get-marker-value-success').addClass('show');
                    })
                    .catch(error => console.log('error:', error));
                }
                else{

                }
            }
        </script>

在服务器端,

var listingRouter = require('./routes/listing');
app.use('/listing', listingRouter);

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Methods",
    "OPTIONS, GET, POST, PUT, PATCH, DELETE" // what matters here is that OPTIONS is present
  );
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
  next();
});

app.listen(port, () => {
  console.log(`App listening at http://localhost:${port}`)
})

路线 - 列表

router.post('/add_listing', function(req, res) {
  console.log("Post Request");
  console.log(req.body);
    const name = req.body.name;
    const phone = req.body.phone;
    const email = req.body.email;
    const address = req.body.address;
    const date = new Date();

    const newListing = new Listing({
      name,
      phone,
      email,
      address,
      date,
    });
    newListing.save()
      .then(() => res.json('Listing added!'))
      .catch(err => res.status(400).json('Error: ' + err));
});

代码在本地运行良好,但在 Heroku 中出现问题。

【问题讨论】:

    标签: javascript node.js heroku cors


    【解决方案1】:

    客户端的 url 指向你需要它指向你的 heroku 服务器的本地主机

      let url="http://localhost:3000/listing/add_listing";
    

    还可以查看有关如何使用 heroku 的教程 您还需要确保您的数据库已连接到 heroku 服务器 您可以在此处获得有关如何部署到 heroku 的更多信息: https://devcenter.heroku.com/articles/getting-started-with-nodejs#deploy-the-app

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 2019-07-23
      • 2016-12-03
      • 1970-01-01
      • 2021-01-20
      • 2021-12-30
      相关资源
      最近更新 更多