node.js - 简单的获取 API 不工作 Node express with angular
问题描述
我有一个带有 node express 和 angular 的项目,似乎无论我做什么,我都无法让最终产品正确地发出 get 请求。我有一个未完成的项目,请求有效。我真的看不出这两个项目之间有什么区别。
我的服务器文件:
const express = require('express');
const path = require('path');
const app = express();
const routes = require('./server/routes/routes');
app.use(express.static(path.join(__dirname, 'dist')));
app.use('/routes', routes);
app.get('*', (req, res)=>{
res.sendFile(path.join(__dirname, 'dist/index.html'))
});
const port = process.env.PORT || 4600;
app.listen(port, (req, res)=>{
console.log(`RUNNING on port ${port}`);
});
控制台日志也不会发生,因为请求导致错误
我的 route.js 文件:
const express = require('express');
const router = express.Router();
const axious = require('axios');
const PostAPI = 'https://jsonplaceholder.typicode.com';
router.get('/', (req, res) => {
axious.get(`${PostAPI}/posts`).then(posts => {
console.log(posts.data);
res.status(200).json(posts.data);
}).catch(error => {
res.status(500).send(error);
})
});
module.exports = router;
我在运行应用程序时没有收到任何错误或任何路径错误。但是我也再也没有得到 API 的结果了……我不确定这里出了什么问题。我的整个项目的副本在这个 github 上,所以你可以看到项目的角度部分。
https://github.com/ana-acoss/Node-Express-and-Angular- 我只有在运行我的应用程序时才会得到这个
我一直在尝试并试图找出问题所在,但仍然没有。
解决方案
您的配置正在将响应处理程序映射到/routes
,但是您正在请求/posts
?我认为你只需要更改routes
为posts
然后你应该打你的后端电话。
app.use('/routes', routes);
app.get('*', (req, res)=>{
res.sendFile(path.join(__dirname, 'dist/index.html'))
});
推荐阅读
- java - 序列化后arraylist如何保存数据
- swift - 使用另一个字典更新字典的某些值(Swift 4)
- reactjs - 在 API 中访问想要的数据?
- bash - 带参数扩展的双冒号有什么作用?
- python - 如何测试任何字符串是否在列表中?
- sql - 如何在 SQL Server 中的触发器上分隔字符串
- reactjs - renderStatic 的头盔错误
- java - 如何解决 spring-boot 中的 URI 编码问题?
- android - 具有应用内区域设置更改的 Android App Bundle
- python - 带 None 的 f 字符串格式说明符抛出 TypeError