首页 文章

在Heroku部署中,React axios调用Express API

提问于
浏览
0

我有一个使用create-react-app构建的React todo应用程序,我构建了一个简单的快速服务器来查询mongoDB以获取所有约会对象 . 当我在我的机器上运行时,它的工作方式与预期一样 . 前端在 localhost:3000 上旋转,服务器在 localhost:3001 上旋转 . 我使用axios向 localhost:3000/api/appointments 发出get请求,将所有约会加载到App.js状态 . 我将它上传到Heroku,我在请求时遇到了CORS错误 . 之后,我尝试在请求中使用路由'api/appointments',并且我可以提出的每个排列都会响应404错误 . node.env变量在哪里启动Heroku上的服务器?如何从带有axios的React应用程序中调用它?

如果它有帮助,在不同的上下文中的相同问题:当我在我的机器上运行应用程序并使用Postman访问它时,我可以 GET localhost:3001/api/appointments 并且它正如我所期望的那样从数据库返回一个JSON对象数组 . 当我部署到Heroku时 GET https://appointment-ledger-map.herokuapp.com/api/appointments 返回index.html的所有标记 . 我认为这意味着api服务器启动并运行,因为它响应,但为什么它没有按预期响应JSON对象数组?

// server.js

var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var Appointment = require('./model/appointments');
//and create our instances
var app = express();
var router = express.Router();
//set our port to either a predetermined port number if you have set 
//it up, or 3001
var nodeEnv = process.env.NODE_ENV || 'development';
var port = process.env.PORT || 3001;
var host = process.env.HOST || '0.0.0.0';
//db config
mongoose.connect('mongodb://josh11:josh11@ds133162.mlab.com:33162/heroku_tl016m5d');
//now we should configure the API to use bodyParser and look for 
//JSON data in the request body
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//To prevent errors from Cross Origin Resource Sharing, we will set 
//our headers to allow CORS with middleware like so:
app.use(function(req, res, next) {
 res.setHeader('Access-Control-Allow-Origin', '*');
 res.setHeader('Access-Control-Allow-Credentials', 'true');
 res.setHeader('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT,DELETE');
 res.setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
//and remove cacheing so we get the most recent appointments
 res.setHeader('Cache-Control', 'no-cache');
 next();
});
//now we can set the route path & initialize the API
router.get('/', function(req, res) {
 res.send({ message: 'API Initialized!'});
 console.log('Api initialized');
});
//Use our router configuration when we call /api
app.use('/api', router);
//starts the server and listens for requests
app.listen(port, host, function() {
 console.log(`api running on port ${port}`);
});
//adding the /appointments route to our /api router
router.route('/api/appointments')
 //retrieve all appointments from the database
 .get(function(req, res) {
 //looks at our Appointment Schema
 Appointment.find(function(err, appointments) {
 if (err)
 res.send(err);
 //responds with a json object of our database appointments.
 res.send(appointments)
});
console.log(appointments);
 })
 //post new appointment to the database
 .post(function(req, res) {
 var appointment = new Appointment();
 //body parser lets us use the req.body
  appointment.appointmentTitle = req.body.appointmentTitle;
  appointment.appointmentDate = req.body.appointmentDate;
  appointment.appointmentTime = req.body.appointmentTime;
  appointment.appointmentDescription = req.body.appointmentDescription;
  appointment.appointmentDestination = req.body.appointmentDestination;
  appointment.appointmentOrigin = req.body.appointmentOrigin;
  appointment.travelMode = req.body.travelMode;
appointment.save(function(err) {
 if (err)
 res.send(err);
 res.send({ message: 'Appointment successfully added!' });
 });
 });

// App.js

loadAppointments() {
    axios.get('/api/appointments')
    .then(res => {
      this.setState({ 
        appointments: res.data,
        filteredAppointments: res.data
       });
    })
  }

1 回答

  • 1
    npm install cors --save
    

    然后

    var cors = require('cors');
    

    最后

    mongoose.connect('mongodb://josh11:josh11@ds133162.mlab.com:33162/heroku_tl016m5d');
    //now we should configure the API to use bodyParser and look for 
    //JSON data in the request body
    app.use(cors()); **//Must be before BodyParser**
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());
    //To prevent errors from Cross Origin Resource Sharing, we will set 
    //our headers to allow CORS with middleware like so:
    

    重新部署它瞧瞧:)

    希望它能帮助你

相关问题