2017-09-16 56 views
0

我真的很陌生,我试图了解发送静态文件是如何工作的。我设法为我的索引文件提供服务,但是我无法将其他文件作为GET请求的响应。Node/Express根据请求发送静态文件

app.use(express.static(path.join(__dirname, '/client/build'))) 

app.get('/', (req, res) => { 
    res.sendFile(path.resolve(__dirname, '.', 'client/build/', 'index.html')) 
    res.end() 
}) 

app.get('/portfolio', (req, res) => { 
    const person = req.query.name 
    var filePath = __dirname + '/client/build/' + person + '/' + 'index.html' 
    res.sendFile(filePath) 
    res.end() 
}) 

我发现了类似的问题,但似乎没有任何工作。

我发送请求为:

fetch(`portfolio?name=${who}`) 
+1

你发送给服务器的请求是什么? – alexmac

+0

什么是“人”,你发送给服务器的请求是什么? @alexmac – turmuka

+0

我编辑的问题,请求 取('组合?name = $ {}谁') 其中“谁”是投资组合持有 – Braian

回答

0

有你的代码的几个问题。其中之一就是在文件发送完成之前结束请求,而另一个问题是您没有正确使用方法res.sendFile

尝试这样的事:

app.get('/', (req, res) => { 
    const fileDirectory = path.resolve(__dirname, '.', 'client/build/'); 

    res.sendFile('index.html', {root: fileDirectory}, (err) => { 
    res.end(); 

    if (err) throw(err); 
    }); 
}) 

app.get('/portfolio', (req, res) => { 
    const person = req.query.name 
    const fileDirectory = __dirname + '/client/build/' + person + '/'; 

    res.sendFile('index.html', {root: fileDirectory}, (err) => { 
    res.end(); 

    if (err) throw(err); 
    }); 
}) 

我不建议每当你得到一个扔一个错误,但它至少应该给你一个想法,你如何能得到这个工作。

app.use(express.static(path.join(__dirname, 'client/build/person1'))) 
app.use(express.static(path.join(__dirname, 'client/build/person2'))) 

,把它像这样的观点:

+0

我试过的名称(字符串),但它并没有工作。正如有人指出的,第一个请求处理程序('/')不是必需的,因为express.static会映射路由。但第二个仍然不起作用,如果我把一个console.log它记录的东西,所以请求正在处理,但它不会做任何事情,它会抛出错误 – Braian

0

我终于通过使用此服务器上解决它

<a href='/person1'></a> 
<a href='/person2'></a> 

,因为它似乎,express.static解决路径上的其自己的,所以你不需要自己处理请求来提供静态文件。

如果这不是一个好的解决方案,请注意