Mikheil misha
Mikheil misha

Reputation: 61

How to make a post request at the heroku app

I'm trying to post to Heroku from localhost. Here is the sample script at the JavaScript localhost server:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

axios.post('https://thawing-meadow-45314.herokuapp.com', {}).then(res =>{ //perform operation }) .catch(err=>{ // handel error here. })

Here is Node.js script running on Heroku:

const express = require('express');
const app = express();
const cors = require("cors");
app.use(cors());

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.post('/', (req, res) => {

  console.log('message is delivered');

}); //app.post

const port = process.env.PORT || 3081;

app.listen(port, () => {
  console.log(`Server running on port${port}`);
});

On the command line I use three commands:

Heroku login 
Heroku run bash
node index.js 

The problem is that nothing happens. Heroku app isn't detecting my post request from the localhost. What I have to do?

Upvotes: 1

Views: 7099

Answers (2)

Swapnil Shukla
Swapnil Shukla

Reputation: 229

Remove PORT from Axios request URL.

axios.post('https://thawing-meadow-45314.herokuapp.com', {}).then(res =>{
//perform operation
})
.catch(err=>{
// handel error here.
})

Also, make sure you have enabled CORS on your server. I`ll suggest using cors module if you are not using it and add it to your app middleware like this:

const express = require("express");
const app = express();
const cors = require("cors");

app.use(cors());

app.post("/", (req, res) => {
  // perform operation and return response.
  res.status(200).json({ message: "It worked!" });
});

app.listen(3000, function() {
    console.log("server is running");
  });

And don`t forget to restart the server after making changes.

Upvotes: 0

Chris
Chris

Reputation: 136909

axios.post('https://thawing-meadow-45314.herokuapp.com:55058', {})

Don't post to the port Heroku gives you via the PORT environment variables.

That's the internal port your app needs to bind to, but this is exposed publicly as the standard ports 80 and 443. Leave the port out entirely:

axios.post('https://thawing-meadow-45314.herokuapp.com', {})

Also, don't do this:

On the command line I use three commands:

heroku login
heroku run bash
node index.js

Your server should start up automatically via the start script in your package.json (or a custom command given in your Procfile). Something like

"scripts": {
  "start": "node index.js"
}

in your package.json should do it. Heroku dynos restart frequently, so it's important that they can start up on their own.

Upvotes: 4

Related Questions