首页 > 解决方案 > 关闭路由时出现不可恢复的语法错误

问题描述

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));



app.get('/split/name', (req, res) => {
    var name=req.query.fullName;
    name=name.split(' ');
    var first=name[0];
    var second=name[1];
    res.status(200).json({firstName: first,secondName:second});

});
// end split name

app.get('/calculate/age', (req, res) => {
    var dob = req.query.dob;
    var getAge = (dob) => {
        var today = new Date();
        var birthDate = new Date(dob);
        var age = today.getFullYear() - birthDate.getFullYear();
        var m = today.getMonth() - birthDate.getMonth();
        if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
            age--;
        }
        return age;
    }
    res.status(200).json({age: getAge(dob)});
});// i get the error here

根据问题,我得到的输入是“/split/name?fullName=ritik verma”,我必须将它分成名字和姓氏,第二部分是“/calculate/age?dob=17-04-1999”和我需要计算年龄。

所以我给你一个实际的问题也许应该有帮助

问题:-

创建一个具有以下路由并在端口 3000 上运行的 Express 应用程序 -

Route 1 - GET /split/name - 将 fullName 作为查询参数并给出 firstName 和 lastName 作为输出。

示例输入 - /split/name?fullName=Aditya Kumar

输出 - {

“名字”:“阿迪亚”,

“lastName”:”Kumar”

}

Route 2 - /calculate/age - 以 yyyy-mm-dd 格式获取出生日期并返回此人的年龄。

样本输入 - /calculate/age?dob=1992-02-28

输出 - {

“年龄”:27

}

注意:您不需要使用 app.listen()。这将由系统处理。

标签: javascriptexpress

解决方案


**代码似乎可以正常工作,只需要添加app.listen服务器来监听特定端口 **

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));



app.get('/split/name', (req, res) => {
    var name=req.query.fullName;
    name=name.split(' ');
    var first=name[0];
    var second=name[1];
    res.status(200).json({firstName: first,secondName:second});

});
// end split name

app.get('/calculate/age', (req, res) => {
    var dob = req.query.dob;
    var getAge = (dob) => {
        var today = new Date();
        var birthDate = new Date(dob);
        var age = today.getFullYear() - birthDate.getFullYear();
        var m = today.getMonth() - birthDate.getMonth();
        if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
            age--;
        }
        return age;
    }
    res.status(200).json({age: getAge(dob)});
});// i get the error here

app.listen(3000, ()=>{
    console.log("Server listening port 3000")
})

现在尝试以下任何一项

本地测试 在此处输入图像描述

在此处输入图像描述


推荐阅读