“类型错误:无法读取未定义的属性‘替换’”

时间:2020-12-23 14:24:18

标签: javascript node.js express

我一直在尝试制作我的第一个快速应用程序,但我在使用 range.replace() 时遇到错误,我尝试寻找修复程序,但找不到 这是在我尝试流式传输视频时发生的。 这是我第一次使用 express 所以忽略 app.send() 中的 html 脚本:)

我的代码是:

const express = require('express');
const app = express();
const fs = require('fs')
const path = require('path')
require('dotenv').config();
const { auth, requiresAuth } = require('express-openid-connect');

app.use(
    auth({
        authRequired: false,
        auth0Logout: true,
        issuerBaseURL: process.env.ISSUER_BASE_URL,
        baseURL: process.env.BASE_URL,
        clientID: process.env.CLIENT_ID,
        secret: process.env.SECRET,
    })
);

app.get('/profil', requiresAuth(), (req, res) => {
    const profileJSON = JSON.stringify(req.oidc.user);
    var obj = JSON.parse(profileJSON);
    function emailVerified(){
        if (obj.email_verified == "true"){
            return "Doğrulandı";
        }
        else {
            return "Doğrulanmadı";
        }
    }
    res.send(
        `
        <!DOCTYPE html>
        <head>
            <title>Profil sayfası</title>
        </head>
        <body>
            <h1>${obj.nickname}</h1>
            <img src="${obj.picture}"></img>
            <h2>Gerçek isim: ${obj.name}</h2>
            <h2>E-posta: ${obj.email}</h2>
            <h2>E-Posta Doğeulanma Durumu: ${obj.email_verified}</h2>
            <h2>Ülke: ${obj.locale}<h2>
        </body>
        `
    );
})


app.get('/', (req, res)=>{
    res.send(req.oidc.isAuthenticated() ? `
    <!DOCTYPE html>
    <head>
        <title>Murat Ödev Sayfası</title>
    </head>
    <body>
        <h1>Murat Ödev Sayfası</h1>
        <h2>Giriş Durumu: Giriş yapıldı<h2><a href="/logout">Çıkış yap</a>
        <a href="/profil">Profil sayfası</a>
        <a href="/video">Video test</a>
    </body>
    ` : `
    <!DOCTYPE html>
    <head>
        <title>Murat Ödev Sayfası</title>
    </head>
    <body>
        <h1>Murat Ödev Sayfası</h1>
        <h2>Giriş Durumu: Giriş yapılmadı<h2><a href="/login">Giriş yap</a>
    </body>
    `)
})


app.get('/video', requiresAuth(),(req, res) => {
    const range = req.headers.range;
  if (!range) {
    res.status(400).send("Requires Range header");
  }

  // get video stats (about 61MB)
  const videoPath = "video.mp4";
  const videoSize = fs.statSync("video.mp4").size;

  // Parse Range
  // Example: "bytes=32324-"
  const CHUNK_SIZE = 10 ** 6; // 1MB
  const start = Number(range.replace("/\D/g", ""));
  const end = Math.min(start + CHUNK_SIZE, videoSize - 1);

  // Create headers
  const contentLength = end - start + 1;
  const headers = {
    "Content-Range": `bytes ${start}-${end}/${videoSize}`,
    "Accept-Ranges": "bytes",
    "Content-Length": contentLength,
    "Content-Type": "video/mp4",
  };

  // HTTP Status 206 for Partial Content
  res.writeHead(206, headers);

  // create video read stream for this particular chunk
  const videoStream = fs.createReadStream(videoPath, { start, end });

  // Stream the video chunk to the client
  videoStream.pipe(res);
})

const port = process.env.PORT || 3000;
app.listen(port, () => {
    console.log(`Listening on port ${port}`);
})

错误是:

TypeError: Cannot read property 'replace' of undefined

希望有人能帮到我

2 个答案:

答案 0 :(得分:1)

您执行以下操作以查看是否定义了范围

if (!range) {
  res.status(400).send("Requires Range header");
}

您正在正确地寻找错误条件,但这里的问题是您没有退出,所以它会继续,因此为什么会出现错误。添加return退出函数

if (!range) {
  res.status(400).send("Requires Range header");
  return;
}

答案 1 :(得分:0)

您正在对未定义的变量调用 replace()。如果您调试代码,您可以很容易地看到这一点。

您确实要检查是否定义了 range。如果未定义,则发送 400 状态。但这并没有结束功能。同样,在调试代码时很容易看到这一点。

您应该在 then 块中返回或将其余代码放在 else 块中。

为什么 range 未定义?显然这个标头不在请求中。此外,根据 Express 文档获取标头的官方方法是 req.get('range')