【问题标题】:Sending POST request from localhost to heroku server?将 POST 请求从本地主机发送到 heroku 服务器?
【发布时间】:2017-02-14 10:35:39
【问题描述】:

我正在尝试从我的 React 应用程序发送一个 POST 请求。该应用程序在 localhost:8000 上的节点中本地运行。

我尝试在 localhost:5000 上本地运行,并将服务器应用程序推送到 heroku 网址并尝试发送到该地址。

所以基本上我的问题是; 1. 当我在 localhost 上本地运行我的 react 应用程序时,如何向我的 heroku 服务器发送 POST 请求? 2. 如何在 Heroku 服务器/节点应用程序上接收此 POST 请求?


发送 POST 请求的反应代码:

import React, { Component } from 'react'
import axios from 'axios'

require('styles/_webshopPage/webshop.css')

export default class Checkout extends Component {

  postRequest() {
        let nodeServerURL = 'https://peaceful-mountain-93404.herokuapp.com'
        let reqData = {
            msg: 'hello!',
        }

        // Send a POST request
        axios({
          method: 'post',
          url: nodeServerURL,
          data: reqData
        })
    }

  render() {
    return (
            <div >
                <button onClick={this.postRequest.bind(this)} type="button" name="button">Send req</button>
            </div>
    )
  }
}

我的 Heroku 服务器的代码:

var express = require('express')
var app = express()

app.set('port', (process.env.PORT || 5000))
app.use(express.static(__dirname + '/public'))

app.post('/', function(request, response) {
  response.send('Hello World!')
})

app.listen(app.get('port'), function() {
  console.log("Node app is running at localhost:" + app.get('port'))
})

【问题讨论】:

  • 你的节点在你的 Heroku 上运行良好吗?
  • 我不明白你的问题!
  • 在heroku上你的节点服务器是在5000端口上运行的吗?
  • 我真的不知道,你在哪里看到的?

标签: node.js post reactjs heroku axios


【解决方案1】:

我做过类似的事情..

我认为 Fetch api 与它完美配合。

Fetch 提供了 Request 和 Response 对象(以及与网络请求相关的其他内容)的通用定义。这将允许它们在未来需要的任何地方使用,无论是用于服务工作者、缓存 API 和其他处理或修改请求和响应的类似事物,还是任何可能需要您生成自己的响应的用例以编程方式。

我在这里打了一些随机的例子,希望你能理解 fetch api 是如何工作的

          var data= "somerandom string";
         fetch('http://localhost/react_task/form_send.php', {
                            method: 'post',
                            body: JSON.stringify({
                                Password: data,// this is posted on another server
                            })
                        }).then(function (res) {
                            return res.text();
                        }).then((body)=> {
                           console.log(body)// body can be used to get data from another server
                         });

我认为 fetch 非常有助于从另一台服务器发布和获取数据..

享受编码。

【讨论】:

  • 感谢您的回答。您能解释一下这与 express 库有何不同吗?
猜你喜欢
  • 2019-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-20
  • 1970-01-01
  • 2021-08-26
相关资源
最近更新 更多