-1

我将 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 中存在问题。

4

1 回答 1

-1

客户端的 url 指向 localhost 你需要它指向你的heroku服务器

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

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

于 2021-09-23T21:35:49.577 回答