首页 > 解决方案 > 简单的获取 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- 我只有在运行我的应用程序时才会得到这个 在此处输入图像描述

我一直在尝试并试图找出问题所在,但仍然没有。

标签: node.jsangularexpress

解决方案


您的配置正在将响应处理程序映射到/routes,但是您正在请求/posts?我认为你只需要更改routesposts然后你应该打你的后端电话。

app.use('/routes', routes);

app.get('*', (req, res)=>{
    res.sendFile(path.join(__dirname, 'dist/index.html'))
    });

推荐阅读