我正在尝试了解 Express 以及它如何处理路线。
我设置了一个具有以下结构的域
/
app.js
/public_html
index.html
在 app.js 中,我设置了我的 Express 服务器:
let app = express();
app.post('/list', (request, response) => {
//get data then...
response.send(data)
});
app.use(express.static('public_html'))
app.listen(3000, function(){
console.log('listening');
});
我使用 node app.js
运行应用程序
然后,在 public_html 目录中的 index.html
中,我尝试请求数据。我只是做了一个简单的:
fetch('/list').then(function(response) {
console.log(response)
})
但是我得到了 404 作为响应。
我对以下几件事有点困惑:
我的 Web 服务器(Apache/Ubuntu)默认设置为从 public_html 目录中提供 html。这是否意味着我的整个 Node 应用程序结构需要移至 public_html 文件夹中,并将实际 html 移至
static
文件夹或其他文件夹中?端口怎么样? Node 应用程序监听端口 3000 - 但我不确定如何(或是否)专门向该端口发出请求。
路线路径 - 我正在发布到
/list
,但它应该是../list
吗?
我还没有找到适用于该应用程序的配置。任何帮助,将不胜感激。
最佳答案
使用以下代码。使用ajax代替fetch并且方法必须是POST。 Fetch 不起作用,因为默认是 get 请求。
选项 1
$.ajax({
method: "POST",
url: "/list"
})
.done(function( msg ) {
alert( "Data " + msg );
});
选项 2 仅更改以下代码 => POST 为 GET
app.get('/list', (request, response) => {
//get data then...
response.send(data)
});
选项 3 在获取中使用 POST
fetch("/list",
{
method: "POST"
})
.then(function(data){ alert( "Data " + data ); })
感谢@vesse建议选项 3
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
关于javascript - 请求快速路线时出现 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43765691/