我正在使用React和Node构建一个完整的堆栈应用程序,并且在我部署到Heroku之后,尽管在本地工作,但我的一条API路径给了我503错误。无论出于何种原因,我的所有其他路由在部署后都能正常工作。对于上下文,这曾经是我正在研究的一个小组项目,但我决定重构,以便它能更好地运作。我自己对服务器做了很少的改动,并且在我们之前部署时工作正常(React方面的问题更多)。
我不完全确定我的代码在哪里搞砸了,所以这里是github:https://github.com/H0sway/puppy-finder-app。
这是我的app.js文件。不工作的路线是/ api / puppyfinder。
// Import dependencies
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
const path = require('path');
const bodyParser = require('body-parser');
require('dotenv').config();
// Middleware stuffs
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static('build'));
//API route
app.use('/api/puppy', require('./routes/puppy-routes'));
app.use('/api/opinions', require('./routes/opinion-routes'));
app.use('/api/puppyfinder', require('./routes/puppy-finder-routes'));
app.get('/*', (req,res) => {
res.sendFile(path.join(__dirname + '/index.html'))
});
// Setting up the port
app.listen(PORT, () => {
console.log(`Live on port ${PORT} but also it's the Shrek movie`);
});
这里是React组件中我试图调用它的方法。
// changes the redirect state so the component knows to redirect to the results page
handleSubmit(event) {
event.preventDefault();
// Post to the puppyfinder controller, which will make a get request to the puppy finder API
// Sends the breed and zipcode to the controller
axios({
method: 'POST',
url: '/api/puppyfinder',
data: {
breed: this.state.breed,
zipcode: this.state.zipcode,
},
})
// Checks to see if puppy data was returned by putting it into an array
.then(puppyData => {
console.log(puppyData.data.data.pet);
if (puppyData.data.data.pet.length) {
this.setState({
puppiesLoaded: true,
puppyData: puppyData.data.data.pet,
});
}
else {
alert(`Sorry, but we couldn't find any ${this.state.breed} dogs nearby ${this.state.zipcode}. Maybe try something else?`)
}
})
.catch(err => {
console.log('puppyfinder call error', err);
})
}
编辑:我一直在仔细查看heroku日志,这是我尝试发布到服务器时的内容。这让我觉得这个问题可能在我的控制器中,但是当我作为一个组部署并且从那时起我没有更改该文件时它工作正常。仍在当地工作。
2018-04-03T16:43:30.656152+00:00 app[web.1]: inside puppy finder API call error TypeError: Cannot read property 'pets' of undefined
2018-04-03T16:43:30.656164+00:00 app[web.1]: at axios.then.allTheDogs (/app/controllers/puppy-finder-controller.js:12:43)
2018-04-03T16:43:30.656169+00:00 app[web.1]: at process._tickCallback (internal/process/next_tick.js:118:7)
2018-04-03T16:43:30.656166+00:00 app[web.1]: at <anonymous>
2018-04-03T16:44:00.622922+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=POST path="/api/puppyfinder" host=fathomless-bayou-33817.herokuapp.com request_id=b008d8bd-750e-4681-89e5-7fcf1999dcfe fwd="100.12.160.42" dyno=web.1 connect=1ms service=30001ms status=503 bytes=0 protocol=https
答案 0 :(得分:0)
想出来,没有为我正在使用的第三方API设置我的私有API密钥。在我的.env文件中本地设置,但在heroku上没有。为了将来参考,请使用$ heroku config:set VARIABLE=value
设置放入.env文件的任何内容。