node.js - 我可以在为服务器提供 API 的同时提供静态文件吗?

标签 node.js web backend vue.js

所以我对 Web 开发还很陌生,现在我和我更面向 Web 的 friend 开始了一个项目,他把所有类型的框架都扔给我了。我们正在做 Vuejs、jade、stylus 和 jeet。对于新手来说,这当然很令人困惑,因为没有 Vuejs 示例使用 jade,没有 jade 示例使用 vuejs,等等。

但是,对于这个项目,我们需要一个后端来处理对 Google map 的 api 调用、保存内容等。我们都没有这方面的经验,我尝试用 Rust 构建它并让它与 api 部分一起工作但我无法设法提供文件,导致我们尝试使用 http 服务器提供文件,然后从客户端对 Rust 后端进行 api 调用。这导致了问题,因为我们必须执行我没有开始工作的 CORS 请求(?)。

抱歉,背景很长,这一切都归结为一个问题:我如何提供静态文件,同时可以对 Google map 进行 API 调用并将内容存储在数据库中?我找到的所有示例似乎都假设您正在使用模板生成提供给最终用户的文件?

我该如何解决这个问题?我的 friend 已经完成了前端的大部分工作,只需使用 npm 包“http-server”即可工作

最佳答案

重要的部分在 app.js 文件中,确保你的服务器路由在顶部定义,然后客户端构建静态文件,如下所示。

var express = require('express');
var bodyParser = require('body-parser');
const path = require('path');

// put server express routes at the beginning //
var app = express();
var router = require('./routes')(); 
app.use('/api', router);
// put server express routes at the beginning //

//Serve the static files from the React app
app.use(express.static(path.join(__dirname, '/../build')));
// Handles any requests that don't match the ones above
app.get('*', (req,res) =>{
    console.log(res);
    res.sendFile(path.join(__dirname+'/../build/index.html'));
});

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.port || 3300

app.listen(port, () => {
    console.log("Hi This port is running");
});

app.get('/', function(req, res){
    if(req.session){
        console.log(req.session);
    }
    console.log('ok');

});

也在 package.json 文件中,

添加代理来路由它

"proxy": "http://localhost:3300",

关于node.js - 我可以在为服务器提供 API 的同时提供静态文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36667343/

相关文章:

javascript - 在 javascript 中调用 php 的替代方案?

html - Bootstrap 网格不是居中对齐的问题

function - Context struct 在 golang gin 框架中如何工作?

node.js - Nodejs : how to redirect subdomains to ports?

centos - 如何在 Centos 上安装 OctoberCMS?

node.js - 安装请求模块时出现错误

javascript - 小鹿交易遗失的藏品

javascript - Node.JS:execFile ENOENT

javascript - WebRTC 重新协商对等连接以切换流

php - 如何使用 Laravel 5.0 作为后端来管理 session