Axios Api calls in Heroku

笑着哭i 提交于 2021-02-04 21:44:00

问题


I've deployed my app to heroku and I have it connected to mongoLab. My problem is my API calls using axios wont't work with Heroku because they are still set up locally. Is there a dynamic env variable I have to replace baseURL with for it to work? I tried researching this with no luck.

See Code below

export default {


  saveClient: function(clientData) {
    return axios({
method:"post",
url:"/api/saveClient",
baseURL:"http://localhost:3001",
data:clientData
    })

  }

----------------------
server.js is below



const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const app = express();
const PORT = process.env.PORT || 3001;
const cors = require("cors")
app.use(cors())
// Configure body parser for AJAX requests
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Serve up static assets
app.use(express.static("client/build"));

var apiRoutes = require("./controllers/clientController.js");
var validatorRoutes = require("./controllers/validatorRoutes.js")
app.use("auth",validatorRoutes)
app.use("/api", apiRoutes);
mongoose.Promise = global.Promise;
// Connect to the Mongo DB
mongoose.connect(
  process.env.MONGODB_URI || "mongodb://skillBuilder:qwerty123@ds143707.mlab.com:43707/heroku_2s9vp225",
  {
    useMongoClient: true
  }
);

// Start the API server
app.listen(PORT, function() {
  console.log(`🌎  ==> API Server now listening on PORT ${PORT}!`);
});


回答1:


You can actually remove the baseUrl option entirely and use just the relative URL '/api/saveClient'. This will work for both your dev and production environment. When you use a relative url axios will default to http://your-app-name.herokuapp.com/api/saveClient.

However, if you had to make the baseUrl explicit, the appropriate baseUrl would be: http://your-app-name.herokuapp.com. To avoid hardcoding this you could try something like:

baseUrl = process.env.baseURL || "http://localhost:3001"

Heroku lets you set environment variables in an easy fashion in their console at dashboard.heroku.com/apps/your-app-name/settings. I don't think you'll need this, but it's good to know as your app grows and you want to configure your production environment more easily.



来源:https://stackoverflow.com/questions/47164330/axios-api-calls-in-heroku

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!