我在Heroku上部署了Express应用程序,并且在本地成功运行的AJAX调用不再在已部署的应用程序上运行。
例如,当AJAX调用的URL为http://localhost:3001/api/trusts时,该调用成功返回。
但是,当已部署的应用程序中的AJAX调用的网址为https://someapp.herokuapp.com/api/trusts时,会给我404错误。
如何在AJAX调用中更正我的网址?我机智了。
这是我的server.js:
//server.js
'use strict'
//first we import our dependencies...
var express = require('express');
var mongoose = require('mongoose');
var path = require('path');
var bodyParser = require('body-parser');
import sitesRoutes from './src/routes/sitesRoutes';
import trustsRoutes from './src/routes/trustsRoutes';
//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 port = process.env.API_PORT || 3001;
//db config
var mongoDB = 'mongodb://SOMEUSERNAME:SOMEPASSWORD!@XXX.mlab.com:XXX/XXX';
mongoose.connect(mongoDB);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
//now we should configure the API to use bodyParser and look for JSON data in the request body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//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 comments
res.setHeader('Cache-Control', 'no-cache');
next();
});
if (process.env.NODE_ENV === 'production') {
app.get(/^\/(?!api).*/, (req, res) => { // don't serve react app to api routes
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
};
app.use('/api', router);
sitesRoutes(router);
trustsRoutes(router);
//starts the server and listens for requests
app.listen(port, function() {
console.log(`api running on port ${port}`);
});
答案 0 :(得分:0)
我认为问题是您的端口号。根据文档,您应该使用<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/v/dt/dt-1.10.18/datatables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.18/datatables.min.css"/>
<table id="groupAlphaList" class="display" width="100%"></table>
环境变量中的端口号Heroku规定。
所以也许尝试更改:
PORT
到
var port = process.env.API_PORT || 3001;