代码之家  ›  专栏  ›  技术社区  ›  twocents

express API/react路由问题

  •  0
  • twocents  · 技术社区  · 8 年前

    我有个问题 未使用适当的路由 在我的React前端/express server API应用程序中。 从react work获取请求,就像从Postman获取请求一样。

    我的问题是 :何时 从浏览器访问api路由时,始终会发送react应用程序 .

    路线

    GET /api/new
    取一个参数 url ie http://www.youtube.com
    样本请求: api/new?url=http://www.youtube.com

    回答
    例如 {short_link: http://localhost:8080/api/150} (150为唯一ID。)

    GET /api/:id
    取一个参数 id 唯一编号,例如150
    样本请求: api/150

    回答

    1. 在DB中查找id,找到短链接
    2. res.redirect(http://www.youtube.com)

    这是我的 repo

    // server/index.js
    const routes = require('./routes/index');
    app.use('/', routes);
    
    // server/routes/index.js
    router.use(express.static(path.resolve(__dirname, '../../client/build')));
    
    router.use('/api/new', catchErrors(link.setLink)) 
    router.use('/api/:id', catchErrors(link.getLink)) 
    router.use('/api/', catchErrors(index)) 
    
    // All remaining requests return the front end
    router.use('/', function(request, response) {
        response.sendFile(path.resolve(__dirname, '../../client/build', 'index.html'));
    });
    
    2 回复  |  直到 8 年前
        1
  •  0
  •   Elliot Blackburn    8 年前

    您的问题与 this question 您的快速路线冲突的地方。

    您告诉您的应用程序将静态内容作为第一条路线。我相信express路由是按照创建的顺序进行过滤的,因此我希望您执行最上面的一行,然后完成请求,而不是向下过滤到您想要的/api端点。

    你应该试着把你的顶线移到 router.use('/api'...); 密码这应该在API端点之后附加静态资产,我认为这应该可以解决这个问题。

        2
  •  0
  •   twocents    8 年前

    我搞定了!

    我的问题是,我的主应用程序文件中有以下代码行:

    // server/index.js
    app.use('/', routes);
    

    我想这会直接指向我的路由文件:

    // server/routes/index.js
    router.use(express.static(path.resolve(__dirname, '../../client/build')));
    
    router.use('/api/new', catchErrors(link.setLink)) 
    router.use('/api/:id', catchErrors(link.getLink)) 
    router.use('/api/', catchErrors(index)) 
    
    // All remaining requests return the front end
    router.use('/', function(request, response) {
        response.sendFile(path.resolve(__dirname, '../../client/build', 'index.html'));
    });
    

    通过更改修复:

    //服务器/索引。js公司
    应用程序。使用(“/”,路线);
    

    // server/index.js
    app.use(routes);
    

    路线不起作用,因为 / + /api/ 不是有效的路线!

    在我的学习中,任何关于这一点的进一步澄清都是非常感谢的。🤓

    推荐文章