簡體   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