GVKun编程网logo

无法使用Express处理Node.js域的异常(无法使用com.mysql.jdbc.driver)

9

对于无法使用Express处理Node.js域的异常感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍无法使用com.mysql.jdbc.driver,并为您提供关于node--express处

对于无法使用Express处理Node.js域的异常感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍无法使用com.mysql.jdbc.driver,并为您提供关于node --express处理get和post、Node JS Express处理多个请求、node.js + express处理上传文件接口demo、Node.js Express express.json和express.urlencoded表单提交的有用信息。

本文目录一览:

无法使用Express处理Node.js域的异常(无法使用com.mysql.jdbc.driver)

无法使用Express处理Node.js域的异常(无法使用com.mysql.jdbc.driver)

我想使用Node.js域来捕获异常。到目前为止,它正在运行,但是有一个地方我无法获得域来捕获异常。回调中的exception2是在domain.on(’error’)处理程序中捕获并处理的,但没有捕获exception1。奇怪的是,当抛出exception1时,它不会像我期望的那样关闭Node。这是我的示例应用程序:

var domain = require(''domain'');var request = require(''request'');var express = require(''express'');var serverDomain = domain.create();serverDomain.on(''error'', function(err) {  console.log("Server Domain Error: " + err);});var app;serverDomain.run(function() {  app = express();  app.listen(3000);});app.use(function(req, res, next) {  var reqDomain = domain.create();  reqDomain.add(req);  reqDomain.add(res);  reqDomain.on(''error'', function(err) {    console.log("Req Domain Error: " + err);    reqDomain.dispose();    next(err);  });  next();});app.get(''/'', function(req, res) {  var uri = "http://google.com";  exception1.go();  request.get({url:uri, json: {}},    function (error, response, body) {      if(response.statusCode === 200) {        exception2.go();        res.send(''Success getting google response'');      }    });});

为了使exception2执行,我注释掉了exception 1。

答案1

小编典典

问题在于该异常发生在Connect的路由过程中,该路由在其执行过程中有一个try/catch块,同时还有一个默认的错误处理程序,该错误处理程序在非生产模式下运行时会打印出堆栈跟踪详细信息。由于异常是在Express内部处理的,因此它永远不会到达域的外部层。

它的区别在于,路由exception2的处理程序函数''/''直接由该Connect块执行,与通过Express进行的原始调用位于同一堆栈中。第二个异常发生在
回调中 ,返回了一些I / O操作之后,因此由Node的事件循环I /
O处理程序发起的堆栈执行,因此try/catchExpress的功能无法捕获该异常并保存应用服务器。实际上,如果您注释掉所有域内容,并exception2使其跳闸,则会使Node崩溃。

由于仅将未处理的异常路由到域机制,并且由于在其上方的调用堆栈中exception1try/catch可见的异常,因此将处理该异常,而不将其转发到域。

node --express处理get和post

node --express处理get和post

<!DOCTYPE html>
<html lang="en">
<head>
    
    
    
    <Meta charset="UTF-8">
    <title>Document</title>
</head>

</html><!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <title>Document</title>
    <style>        
    </style>
</head>
<body>
<form action="http://localhost:3000/login" method="get">
    用户名:<input type="text" name="username"><br>
     密码 :<input type="text" name="password"><br>
     <input type="submit" value="提交"></input>
</form>
</body>
</html>

创建public文件夹放入html文件

<!DOCTYPE html>
<html lang="en">
<head>
    
    
    
    <Meta charset="UTF-8">
    <title>Document</title>
</head>

</html><!DOCTYPE html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <title>Document</title>
    <style>        
    </style>
</head>
<body>
<form action="http://localhost:3000/login" method="get">
    用户名:<input type="text" name="username"><br>
     密码 :<input type="text" name="password"><br>
     <input type="submit" value="提交"></input>
</form>
</body>
</html>

 

<!DOCTYPE html> <html lang="en"> <head>                    <Meta charset="UTF-8">     <title>Document</title> </head>
</html><!DOCTYPE html> <html lang="en"> <head>     <Meta charset="UTF-8">     <title>Document</title>     <style>          </style> </head> <body> <form action="http://localhost:3000/login" method="get">     用户名:<input type="text" name="username"><br>      密码 :<input type="text" name="password"><br>      <input type="submit" value="提交"></input> </form> </body> </html>

总结

以上是小编为你收集整理的node --express处理get和post全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

原文地址:https://www.cnblogs.com/hack-ing/p/12112517.html

Node JS Express处理多个请求

Node JS Express处理多个请求

我所拥有的: 我有一个nodejs
express服务器获取端点,该端点依次调用其他耗时的API(例如大约2秒)。我已经通过回调调用了此函数,使得res.send作为回调的一部分被触发。res.send对象打包了一个对象,该对象将在执行这些耗时的API调用的结果之后创建。因此,仅当我从API调用中获得全部信息时,才能发送我的res.send。

一些代表性的代码。

someFunctionCall(params, callback){  // do some asyncronous requests.  Promise.all([requestAsync1(params),requestAsync2(params)]).then  {     // do some operations     callback(response) // callback given with some data from the promise  }}app.get(''/'',function(req, res){ someFunctionCall(params, function(err, data){    res.send(JSON.stringify(data))   }}

我要什么 我希望我的服务器能够处理其它并行输入的GET请求不会被阻挡由于其他功能的REST
API调用。但是问题在于,仅当实现了promise时才会发出回调,这些操作中的每一个都是异步的,但是我的线程将等到所有的操作都执行完毕。并且Node不执行下一个请求的res.send或res.end,就不接受下一个get请求。当我有多个请求进入,每个请求一个接一个地执行时,这成为一个问题。

注意:我不想使用cluster方法,我只是想知道如果没有它,是否有可能做到这一点。

答案1

小编典典

您显然误会了node.js,异步操作和Promise的工作方式。假设长时间运行的异步操作均已使用异步I /
O正确编写,那么您的requestAsync1(params)requestAsync2(params)调用都不会阻塞。这意味着,在等待Promise.all()调用其.then()处理程序以表明这两个异步操作均已完成时,node.js完全可以自由运行任何其他事件或传入请求。承诺本身不会阻塞,因此node.js事件系统可以自由处理其他事件。因此,您根本就没有阻塞问题,或者实际上没有阻塞问题,这不是您在此处询问的原因引起的。

要查看您的代码是否实际被阻塞,可以临时添加一个简单的计时器,将其输出到控制台,如下所示:

let startTime;setInterval(function() {    if (!startTime) {        startTime = Date.now();    }    console.log((Date.now() - startTime) / 1000);}, 100)

当事件循环未阻塞时,这将每100ms输出一个简单的相对时间戳。您显然不会在生产代码中将其保留在代码中,但是当事件循环被阻止时,向您显示可能会很有用。


我确实在您的问题中包含的代码中看到了一个奇怪的语法问题。这段代码:

someFunctionCall(params, callback){  // do some asyncronous requests.  Promise.all([requestAsync1(params),requestAsync2(params)]).then  {     // do some operations     callback(response) // callback given with some data from the promise  }}

应该这样表示:

someFunctionCall(params, callback){  // do some asyncronous requests.  Promise.all([requestAsync1(params),requestAsync2(params)]).then(function(response)  {     // do some operations     callback(response) // callback given with some data from the promise  }});

但是,更好的设计将是仅返回诺言,而不切换回简单的回调。除了允许调用者使用更灵活的Promise方案外,您还“吃”了异步操作或异步操作中可能发生的错误。建议这样做:

someFunctionCall(params) {  // do some asyncronous requests.    return Promise.all([requestAsync1(params),requestAsync2(params)]).then(function(results) {        // further processing of results        // return final resolved value of the promise        return someValue;    });}

然后,呼叫者会这样使用:

someFunctionCall(params).then(function(result) {    // process final result here}).catch(function(err) {    // handle error here});

node.js + express处理上传文件接口demo

node.js + express处理上传文件接口demo

在平时工作和自己写小项目时会遇到需要上传文件的场景,这里使用nodejs搭建服务端接口。

模块

const express = require(''express'');
const app = express();
const cors = require(''cors'');
const multer = require(''multer'');
const fs = require(''fs'');
  • multer是用于处理文件上传的nodejs中间件,主要跟express框架搭配使用,只支持表单MIME编码为multipart/form-data类型的数据请求
  • fs模块用于对系统文件及目录进行读写操作
  • cors用来处理带cookie的跨域请求

接口

const express = require(''express'');
const app = express();
const cors = require(''cors'');
const fs = require(''fs'');
const multer = require(''multer'');

// 引入multer
const upload = multer({
    dest: ''uploads/''
});

morgan.token(''body'', (req: { body: any; }) => {
    return JSON.stringify(req.body);
});

// 托管静态文件,并且加个前缀uploads,为了安全规范
app.use(''/uploads'', express.static(__dirname + ''/uploads''));

// 处理带cookies的跨域请求
app.use(cors({credentials: true, origin: ''http://localhost:8080''}));

// 接口填写,上传文件类型为任何文件
app.post(''/upload'', upload.any(), async (req: any, res: any) => {
    res.header(''Access-Control-Allow-Credentials'', true);
    res.header(''Access-Control-Allow-Origin'', ''http://localhost:8080'');
    res.header(''Access-Control-Allow-Methods'', ''PUT, POST, GET, DELETE, OPTIONS'');
    console.log(req.files[0]);  // 上传的文件信息

	// 保存文件,或者做一些后续文件的处理
    var des_file = "./uploads/" + req.files[0].originalname;
    fs.readFile( req.files[0].path, (err: any, data: any) => {
        fs.writeFile(des_file, data,  (err: any) => {
            if(err){
                console.log(err);
            }else{
                const response = {
                    message: ''File uploaded successfully'',
                    filename: req.files[0].originalname
                };
                res.end(JSON.stringify(response));
            }
        });
    });
})

在这里插入图片描述

总结

以上是小编为你收集整理的node.js + express处理上传文件接口demo全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

原文地址:https://blog.csdn.net/weixin_41935198/article/details/118581430

Node.js Express express.json和express.urlencoded表单提交

Node.js Express express.json和express.urlencoded表单提交

Express(或Connect的)bodyParser中间件被标记为不建议使用,建议用户改为:

app.use(connect.urlencoded())
app.use(connect.json())

但是,当我在Action中运行Node.js的一个例子时,我使用curl来填写本书中建议的表单:

curl -F entry[title]='Ho ho ho' -F entry[body]='santa loves you' http://abc:123@127.0.0.1:3000/api/entry

它不工作req.body没有定义。我错过了什么吗?它适用于bodyParser。

编辑:解决方案从Express 4

这样解析json:

var bodyParser = require('body-parser');

...

app.use(bodyParser.json());

以这种方式解码urlencoded body:

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

然后没有废弃警告。 extended:true(默认)使用qs模块,false使用querystring模块来解析主体。

不要使用app.use(bodyParser()),该用法现在已被弃用。

解决方法

bodyParser其实是三个中间件的组成(见 documentation和 relevant source code):json,urlencoded和multipart:

> json解析application / json请求体
> urlencoded解析x-ww-form-urlencoded请求体
>和multipart解析multipart / form-data请求主体,这是您感兴趣的。

如果只指定json和urlencoded的中间件,表单数据将不会被任何中间件解析,因此req.body不会被定义。然后,您需要添加一个能够解析形式数据的中间件,例如强大的,忙碌的或多方的(如connect‘s documentation所述)。

这是一个例子,使用multiparty

var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
app.use('/url/that/accepts/form-data',multipartMiddleware);
app.post('/url/that/accepts/form-data',function(req,resp) {
    console.log(req.body,req.files);
});

不要忘记,通过使用这样的中间件,您允许任何人将文件上传到您的服务器:然后您有责任处理(并删除)这些文件。

关于无法使用Express处理Node.js域的异常无法使用com.mysql.jdbc.driver的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于node --express处理get和post、Node JS Express处理多个请求、node.js + express处理上传文件接口demo、Node.js Express express.json和express.urlencoded表单提交等相关内容,可以在本站寻找。

本文标签: