繁体   English   中英

带有Node.JS Express的AWS X-Ray和请求

[英]AWS X-Ray with Node.JS Express and request

因此,我正在尝试通过我的Express应用程序实现X射线。 我有我的app.js文件,并且内部引用了一个路由器文件。

我的项目结构:
project/ routes/ index.js app.js

app.js:

var indexRouter = require("./routes/index")
...
app.use("/", indexRouter)
...

index.js:

const AWSXRay = require("aws-xray-sdk")
const request = require("request")

router.post("/xray", async function(req, res, next) {
    let app = req.app
    app.use(AWSXRay.express.openSegment("MyApp"))

    try {
        console.log(AWSXRay.getSegment()) // this succesfully gets segment
        AWSXRay.captureAsyncFunc("send", function(subsegment) {
            request.get("http://www.google.com", { XRaySegment: subsegment }, function() {
                res.json({
                    success: "success"
                })
                subsegment.close()
        })
    } catch (err) {
        next(err)
    }
    app.use(AWSXRay.express.closeSegment())
})

我正在关注自动模式示例:通过AWS文档( https://docs.aws.amazon.com/xray-sdk-for-nodejs/latest/reference/index.html )中的异步函数调用进行捕获,但是我出现错误消息:“无法从上下文中获取当前子/段。”


谁能让我知道我在做什么错?

您应该将app.use(AWSXRay.express.openSegment("MyApp"))代码移动到app.use("/", indexRouter)上方的app.js

然后将app.use(AWSXRay.express.closeSegment())移动到app.use(AWSXRay.express.closeSegment()) app.use("/", indexRouter)

如果您查看提供的链接中引用的代码,则会注意到openSegmentcloseSegment在路线之外,而不是在路线内(因为您当前拥有它们)

链接中的代码可供参考:

var app = express();

//...

var AWSXRay = require('aws-xray-sdk');

app.use(AWSXRay.express.openSegment('defaultName'));               //required at the start of your routes

app.get('/', function (req, res) {
  res.render('index');
});

app.use(AWSXRay.express.closeSegment());   //Required at the end of your routes / first in error handling routes

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM