html5 - node.js下载失败,求大神解释

查看:101
本文介绍了html5 - node.js下载失败,求大神解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

使用express框架下载文件,但是失败了,直接看代码

<!DOCTYPE html>
<html>
<head>
    <title>express 主页</title>
    <meta charset="utf-8">
    <script type="text/javascript" src="jquery.min.js"></script>
</head>
<body>
<div>
I love you!
</div>
<button>click there to download a pictutre</button>
<script type="text/javascript">
$(function(){
    $('button').click(function(){
            $.ajax({
                url:'/download',
                type:'get',
                success:function(result){
                    alert("Resquest has been received!");
                }
            })
    })
})

</script>

</body>
</html>

以下是node.js代码

    var express = require("express");
var app = express();

app.use(express.static('public'));
app.locals.title = "My app";
app.get("/",function(req,res){

console.log("resquest has been received!");

res.sendFile("public/index.html");
res.end();
})

app.get("/download",function(req,res){

    
    res.download('public/example.jpg','example.jpg',function(err){
        if(err)
            console.log(err);
        else
            console.log("download successfully");
    });
})
app.listen(3000);

console.log("OK");


求解疑

解决方案

index.html

<!DOCTYPE html>
<html>
<head>
    <title>express 主页</title>
    <meta charset="utf-8">
    <script type="text/javascript" src="jquery.min.js"></script>
</head>
<body>
<div>
I love you!
</div>
    <a href="/download" download>下载</a>
</body>
</html>

node.js

var express = require("express");
var app = express();

app.use(express.static('public'));
app.locals.title = "My app";
app.get("/",function(req,res){

console.log("resquest has been received!");

res.sendFile("public/index.html");
res.end();
})

app.get("/download",function(req,res){

    res.download('public/example.jpg', 'example.jpg',function(err){
        if(err)
            console.log(err);
        else
            console.log("download successfully");
    });
})
app.listen(3000, function(err) {
  if(err) console.error(err);
  console.log("OK");
});

你可以浏览器单独访问http://localhost:3000/download看看能不能下载下来,你现在直接404后台服务都没ready,先别前后端的联调吧。

这篇关于html5 - node.js下载失败,求大神解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆