Я реализую простой WebAPI в облачных функциях Firebase с помощью Express TypeScript. Мой код следующий.
import * as functions from 'firebase-functions';
import * as express from 'express';
const app = express()
app.post('/', (req, res) => {
var resText: string = "NotEmpty"
const text: string = req.body.text
if (isEmpty(text)) {
resText = "Empty"
}
console.info("text: ", text)
console.info("resText: ", resText)
res.send("Echo " + resText)
})
exports.api = functions.https.onRequest(app)
const isEmpty = (str: string): boolean => {
console.info("str: ", str, "+++")
const trimedStr = str.trim()
const result = (trimedStr === null || trimedStr === "")
console.info("result: ", result)
return result
}
Сборка для преобразования машинописного текста в javascript работала нормально. Однако, когда я использовал метод POST, произошла следующая ошибка.
> TypeError: Cannot read property 'trim' of undefined
> at isEmpty (/Users/kenny/Test/firebase_functions/functions/lib/index.js:22:27)
> at app.post (/Users/kenny/Test/firebase_functions/functions/lib/index.js:9:9)
> at Layer.handle [as handle_request] (/Users/kenny/Test/firebase_functions/functions/node_modules/expr
ess/lib/router/layer.js:95:5)
> at next (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/route.js:137:
13)
> at Route.dispatch (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/rou
te.js:112:3)
> at Layer.handle [as handle_request] (/Users/kenny/Test/firebase_functions/functions/node_modules/expr
ess/lib/router/layer.js:95:5)
> at /Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/index.js:281:22
> at Function.process_params (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/r
outer/index.js:335:12)
> at next (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/router/index.js:275:
10)
> at expressInit (/Users/kenny/Test/firebase_functions/functions/node_modules/express/lib/middleware/in
it.js:40:5)
Как я могу исправить эту ошибку?
Переменная «текст» ничего не содержит. Потому что «req.body.text» имеет неопределенное значение. Проверьте свой req.body, имеет ли он значение или нет.
Просто проверьте, действительно ли str
пусто в isEmpty
Добавьте к нему if (!str) return true
.
Это будет выглядеть так:
const isEmpty = (str: string): boolean => {
console.info("str: ", str, "+++")
if (!str) return true;
const trimedStr = str.trim()
const result = (trimedStr === null || trimedStr === "")
console.info("result: ", result)
return result
}
В JavaScript истинное значение — это значение, которое считается истинным при встрече в логическом контексте. Все значения являются истинными, если только они не определены как ложные (т. е. за исключением ложных, 0, "", null, undefined и NaN).
так почему вы не можете использовать, как показано ниже?
if (!text) {
resText = "Empty"
}
Прежде всего вам нужно понять, почему req.body.text имеет значение null или undefined, а затем вы выполняете пустую проверку, как показано ниже.
const isEmpty = (str: string): boolean => {
console.info("str: ", str, "+++")
const result = (!str || str.toString().trim() === ""); // converting toString because there chance body.text can be a number
console.info("result: ", result)
return result
}
Ваша проблема в том, что isEmpty
не готов принимать вещи, которые не являются строкой.
Быстрая починка: установить значение по умолчанию
const isEmpty = (str=''): boolean => {
// code...
}
Лучшее решение: проверьте свои данные.
При разработке любого API вам необходимо проверять входные данные для вашего запроса.
You are working on an API endpoint to create a new user and you will require some data along with the request like firstname, lastname, age and birthdate for the user you are about to create. Obviously, passing Sally as value for age or 53 for birthdate won't get things rolling in the right direction. You really don't want bad data making its way through your application so what do you do? The answer is Data Validation. Reference.
Я сделаю быстрый пример для этого случая, используя Джой:
// code...
const schema = {
text: Joi.string()
};
app.post('/', (req, res) => {
//my code starts here
const data = req.body;
const {error, value} = Joi.validate(data, schema);
if (error) {
return res.status(400).json(error);
}
// ends here
var resText: string = "NotEmpty"
const text: string = req.body.text
if (isEmpty(text)) {
resText = "Empty"
}
console.info("text: ", text)
console.info("resText: ", resText)
res.send("Echo " + resText)
});
// code...
Похоже, текст пустой. Является ли тип контента текстовым?