Использование Vue 2 и Lua Back-End. Я тестирую свои ошибки и хотел бы разместить пользовательские сообщения об ошибках, которые я определил в user_ubject.lua , чтобы передаваться в мое фронтальное приложение. По какой-то причине, когда сеанс недопустим, вместо моих пользовательских сообщений об ошибках я получаю следующую ошибку в консоли на переднем конце: < /p>
TypeError: Object(...) is not a function< /code> < /p>
Online user.actions.js: 77, который:
console.log(error.toString())
Все журналы от Lua в порядке. Сообщение правильно передается в ответ на repply_error
В моей вкладке сети я вижу ошибку 401, с его ответом {"Ошибка": "Нет токена сеанса"}
Но я не могу получить его в блоке eSsessionValid в моем пользовательском. /> user_object.lua
local function respond_error(status, message)
ngx.status = status
ngx.say(cjson.encode({ error = message }))
ngx.exit(status)
end
function BaseObject:IsValidSession()
ngx.log(ngx.INFO, "Start IsValidSession")
local ENDPOINT = "token/introspect"
-- Get the refresh token and access token from cookies
local ck = cookie:new()
local refresh_token, refresh_err = ck:get("refresh_token")
local access_token, access_err = ck:get("access_token")
if not refresh_token then
ngx.log(ngx.WARN, "Refresh token not found in cookie: " .. (refresh_err or "not present"))
if not access_token then
ngx.log(ngx.WARN, "Access token not found in cookie: " .. (access_err or "not present"))
end
end
local token = refresh_token or access_token
if not token then
ngx.log(ngx.ERR, "IsValidSession: no token found in cookies")
return respond_error(ngx.HTTP_UNAUTHORIZED, "No session token")
end
-- Prepare the POST data
local post_data = ngx.encode_args({
client_id = CLIENT_ID,
client_secret = CLIENT_SECRET,
token = token
})
-- Make the HTTP POST request to Keycloak
local res, err = self:KeycloakHttpPost(post_data, ENDPOINT)
if not res then
ngx.log(ngx.ERR, "IsValidSession: unable to contact Kaycloak - " .. (err or "unknown error"))
return respond_error(ngx.HTTP_BAD_GATEWAY, "Authentication server unavailable")
end
-- Handle the response
ngx.log(ngx.INFO, "IsValidSession: Received validate response from Keycloak with status: " .. res.status)
if res.status == 400 then
return respond_error(ngx.HTTP_BAD_REQUEST, "Invalid session check")
elseif res.status == 401 then
return respond_error(ngx.ngx.HTTP_UNAUTHORIZED, "Unauthorized session")
elseif res.status == 500 then
return respond_error(ngx.HTTP_BAD_GATEWAY, "Authentication server error")
elseif res.status ~= 200 then
return respond_error(res.status, "Unexpected auth response")
end
local body = cjson.decode(res.body)
ngx.log(ngx.INFO, "BODY: " .. cjson.encode(body))
if not body then
ngx.log(ngx.ERR, "IsValidSession: failed to decode JSON response")
return false, "Invalid response format"
end
if body.active == true then
ngx.log(ngx.INFO, "IsValidSession: session is active")
return true, "Active session"
else
ngx.log(ngx.INFO, "IsValidSession: session is inactive or expired")
return false, "Inactive session"
end
end
Api.lua
local function is_valid_session()
return UserModel:IsValidSession()
end
r:match({
POST = {
["/api/keycloak/session/validate"] = is_valid_session
...
user.actions.js
isSessionValid ({ dispatch }) {
return axios.post('/api/keycloak/session/validate')
.then(() => {
if (!refreshIntervalId) {
dispatch('startAccesTokenRefreshLoop')
}
return axios.get('/api/keycloak/me', { withCredentials: true })
})
.then((response) => {
dispatch('MessagesModule/addMessage', { text: 'Welcome back ' + response?.data?.username || 'User', color: 'info' }, { root: true })
return dispatch('setUserData', { userData: response.data });
})
.catch((error) => {
console.log(error.toString())
if (refreshIntervalId) {
clearInterval(refreshIntervalId);
refreshIntervalId = null;
}
dispatch('clearUserData', {});
return false;
});
},
Подробнее здесь: https://stackoverflow.com/questions/796 ... ion-instea
Нет ошибок в блоке Catch - это только «TypeError: Object (...) не является функцией» вместо этого ⇐ Javascript
Форум по Javascript
1749134046
Anonymous
Использование Vue 2 и Lua Back-End. Я тестирую свои ошибки и хотел бы разместить пользовательские сообщения об ошибках, которые я определил в user_ubject.lua , чтобы передаваться в мое фронтальное приложение. По какой-то причине, когда сеанс недопустим, вместо моих пользовательских сообщений об ошибках я получаю следующую ошибку в консоли на переднем конце: < /p>
TypeError: Object(...) is not a function< /code> < /p>
Online user.actions.js: 77, который:
console.log(error.toString())
Все журналы от Lua в порядке. Сообщение правильно передается в ответ на repply_error
В моей вкладке сети я вижу ошибку 401, с его ответом {"Ошибка": "Нет токена сеанса"}
Но я не могу получить его в блоке eSsessionValid в моем пользовательском. />[b] user_object.lua[/b]
local function respond_error(status, message)
ngx.status = status
ngx.say(cjson.encode({ error = message }))
ngx.exit(status)
end
function BaseObject:IsValidSession()
ngx.log(ngx.INFO, "Start IsValidSession")
local ENDPOINT = "token/introspect"
-- Get the refresh token and access token from cookies
local ck = cookie:new()
local refresh_token, refresh_err = ck:get("refresh_token")
local access_token, access_err = ck:get("access_token")
if not refresh_token then
ngx.log(ngx.WARN, "Refresh token not found in cookie: " .. (refresh_err or "not present"))
if not access_token then
ngx.log(ngx.WARN, "Access token not found in cookie: " .. (access_err or "not present"))
end
end
local token = refresh_token or access_token
if not token then
ngx.log(ngx.ERR, "IsValidSession: no token found in cookies")
return respond_error(ngx.HTTP_UNAUTHORIZED, "No session token")
end
-- Prepare the POST data
local post_data = ngx.encode_args({
client_id = CLIENT_ID,
client_secret = CLIENT_SECRET,
token = token
})
-- Make the HTTP POST request to Keycloak
local res, err = self:KeycloakHttpPost(post_data, ENDPOINT)
if not res then
ngx.log(ngx.ERR, "IsValidSession: unable to contact Kaycloak - " .. (err or "unknown error"))
return respond_error(ngx.HTTP_BAD_GATEWAY, "Authentication server unavailable")
end
-- Handle the response
ngx.log(ngx.INFO, "IsValidSession: Received validate response from Keycloak with status: " .. res.status)
if res.status == 400 then
return respond_error(ngx.HTTP_BAD_REQUEST, "Invalid session check")
elseif res.status == 401 then
return respond_error(ngx.ngx.HTTP_UNAUTHORIZED, "Unauthorized session")
elseif res.status == 500 then
return respond_error(ngx.HTTP_BAD_GATEWAY, "Authentication server error")
elseif res.status ~= 200 then
return respond_error(res.status, "Unexpected auth response")
end
local body = cjson.decode(res.body)
ngx.log(ngx.INFO, "BODY: " .. cjson.encode(body))
if not body then
ngx.log(ngx.ERR, "IsValidSession: failed to decode JSON response")
return false, "Invalid response format"
end
if body.active == true then
ngx.log(ngx.INFO, "IsValidSession: session is active")
return true, "Active session"
else
ngx.log(ngx.INFO, "IsValidSession: session is inactive or expired")
return false, "Inactive session"
end
end
[b] Api.lua[/b]
local function is_valid_session()
return UserModel:IsValidSession()
end
r:match({
POST = {
["/api/keycloak/session/validate"] = is_valid_session
...
[b] user.actions.js[/b]
isSessionValid ({ dispatch }) {
return axios.post('/api/keycloak/session/validate')
.then(() => {
if (!refreshIntervalId) {
dispatch('startAccesTokenRefreshLoop')
}
return axios.get('/api/keycloak/me', { withCredentials: true })
})
.then((response) => {
dispatch('MessagesModule/addMessage', { text: 'Welcome back ' + response?.data?.username || 'User', color: 'info' }, { root: true })
return dispatch('setUserData', { userData: response.data });
})
.catch((error) => {
console.log(error.toString())
if (refreshIntervalId) {
clearInterval(refreshIntervalId);
refreshIntervalId = null;
}
dispatch('clearUserData', {});
return false;
});
},
Подробнее здесь: [url]https://stackoverflow.com/questions/79654682/no-error-in-catch-block-is-but-typeerror-object-is-not-a-function-instea[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия