简体   繁体   中英

ExpressJs posts not work on heroku

i'm having the follwing problem.

When i'm developing my expressjs routes, on localhost my code works perfectly. On postman i have success and on my webapp too.

But the same code not works on heroku. I got 404 always on routes.

I did some tests and i detect the problem is on app.post routes.

When i use app.get the codes works on localhost and on heroku,but using app.post works only in localhost and not on heroku, there i got 404.

My node version and expressjs version is the same on both. This was checked.

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

var cors        = require('cors');
var bodyParser  = require('body-parser');
var morgan      = require('morgan');
var mongoose    = require('mongoose');
var config      = require('./config'); // get our config file

var port = process.env.PORT || 3333;
mongoose.connect(config.database);

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(morgan('dev'));
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('/a', function(req, res) {
  res.json({ message: 'hooray! welcome to our api!' });  
});


app.listen(port);

Message from heroku logs

 at=info method=GET path="/a" host=nx-admin-api.herokuapp.com request_id=60a9fefc-92f1-48fc-a4c8-740e4d61bcd7 fwd="201.53.63.230" dyno=web.1 connect=4ms service=43ms status=404 bytes=322
2016-02-02T02:07:29.306917+00:00 app[web.1]: GET /a 404 46.719 ms - 14

You should use CORS module. Like this;

    ...
    app.use(bodyParser.json());
    app.use(cors());
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM