当我的MEAN堆栈应用程序部署到Heroku时,我在访问API时遇到问题。当我的页面加载时,它会从Mongo中获取一些JSON数据,并将其显示在页面上。它在我的本地环境中有效,但是由于某种原因,将其部署到Heroku时,我的路径似乎不起作用。我已经将路径从本地主机切换到我的heroku Web地址,但这似乎无法解决问题。
我尝试将url从localhost:3000切换到heroku地址,但这似乎无法解决我的问题。
这是我设置的一项服务,用于在页面加载时抓取游戏:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
interface Game {
name: string;
}
@Injectable({
providedIn: 'root'
})
export class GameService {
url = '******.herokuapp.com';
constructor(private http: HttpClient) {}
getAllGames() {
return this.http.get(`${this.url}/api/games`);
}
}
这是我的server.js文件:
mongoose.connect('****** Mongo DB connection')
.then(() => {
console.log('Connected to database!')
})
.catch(() => {
console.log('Connection Failed!')
})
app.use(express.static(__dirname + '/dist/*****'));
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname + '/dist/*****'));
});
app.listen(port, () => {
console.log(`Server Started on port ${port}`);
})
// If we don't take care of the CORS policy, the site will not let our routing be handled
// it's a security thing. What this is saying is, if the request comes from "http://localhost:4200"
// assume that it is a good route and safe for us to use.
// Read more about CORS here: https://www.codecademy.com/articles/what-is-cors
// Add headers
app.use(function (req, res, next) {
// Website we wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'https://*****.herokuapp.com/');
// Request methods we wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers we wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if we need the website to include cookies in the requests sent
// to the API (e.g. in case we use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
app.route('/api/games').get((req, res) => {
Game.find()
.then(games => {
console.log(games);
return res.status(200).json({
message: 'Games fetched successfully',
games: games
});
})
})
加载页面时出现此错误:
unexpected token < in JSON at position 0
这是试图直接导航到API的那个
ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'api/games'
Error: Cannot match any routes. URL Segment: 'api/games'