Feathers errors on a client side - error-handling

My stack react/redux/redux-observable/immutablejs.
Client is rendered by feathers.js using server side rendering.
I use feather-client, after getting 400 (Request doesn't pass validation).
I've got a response in .json format. But for some reasons it's converted to HTML or string.
Error: Order validation failed
at BadRequest.ExtendableBuiltin (bundle.js:106696)
at BadRequest.FeathersError (bundle.js:106771)
at new BadRequest (bundle.js:106812)
at convert (bundle.js:107040)
at toError (bundle.js:106043)
Any ideas how to disable it on a client?
import 'isomorphic-fetch';
import feathers from 'feathers-client';
import authentication from 'feathers-authentication-client';
import config from './config';
let storage = null;
if (!process.env.BROWSER && process.NODE_ENV !== 'test') {
require('localstorage-polyfill');
storage = global.localStorage;
}else{
storage = window.localStorage;
}
const port = process.env.PORT || config.port;
promise.polyfill();
const rest = feathers.rest(`http://localhost:${port}/api`);
const app = feathers()
.configure(feathers.hooks())
.configure(rest.fetch(require('isomorphic-fetch')))
.configure(authentication({ storage }));
export default app;

Spend some minutes fixing it, it's simply implement .toJSON() method...

Related

keycloak-connect / express middleware failes to validate token

My problem: i have a client where users successfully authenticate against keycloak (using keycloak-js) in a "frontend"-client. I then use the "keycloak.token" and forward this to a node/express/keycloak-connect backend. There, the validation of the token seems to fail, i.e. I receive http-403 forbidden. Yet, I do not really understand why the validation fails. Both frontend and backend are member of the same realm, given in the JWT, timings fit, aud/iss/sub also match. Roles are there. Etc.. Unfortunately, I could not find any "debug"-hook in the keycloak middleware to trace (and understand) what happens. Did you every came across? Have I misconfigured the keycloak?
Here is my server code:
keycloak.ts
// #ts-ignore
import Keycloak from "keycloak-connect"
// #ts-ignore
import session from "express-session"
let _keycloak: Keycloak.Keycloak | undefined = undefined;
const memoryStore = new session.MemoryStore();
export function getKeycloak(): Keycloak.Keycloak {
if (!_keycloak) {
_keycloak = new Keycloak({ store: memoryStore }, {
"realm": "ear",
"bearer-only": true,
"auth-server-url": "http://192.168.76.4:40002/auth/",
"ssl-required": "external",
"resource": "ear-backend",
"confidential-port": 0
}); }
return _keycloak;
}
Here is my "main" app - server.ts
import {getKeycloak} from "./keycloak";
import express from "express";
import {Request,Response} from "express";
// #ts-ignore
import cors from "cors";
var app = express();
app.use(cors());
var router = express.Router();
router.get('/user', getKeycloak().protect(), function(req, res){ res.send("Hello User");});
app.use("/test", router);
app.listen(3001);
Here is the bearer token I forward from the client to the server:
authorization: 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJkaDEweTB2WWhnUFVmcWppQVZ3ZVBXUUxTYmpxUWVkaWprZHFBMUVLbUdJIn0.eyJleHAiOjE2NzQzODM5NjgsImlhdCI6MTY3NDM4MzY2OCwiYXV0aF90aW1lIjoxNjc0MzgzNjY4LCJqdGkiOiJmYjhjMTJ kMy0xMmFmLTQ1M2MtYmE1Mi0yNzA3ZDkwYTNkMDEiLCJpc3MiOiJodHRwOi8vMTkyLjE2OC43Ni40OjQwMDAyL2F1dGgvcmVhbG1zL2VhciIsImF1ZCI6ImVhci1iYWNrZW5kIiwic3ViIjoiMDQxNTY1ZDQtYzM0Ni00MDRmLWFmYzYtMjVjMzRmMGViNWM5IiwidHlwIjoiQmVhcmVyIiwiYXpwIjoiZWFyLWZ yb250ZW5kIiwibm9uY2UiOiI2ZGUzOGYzMy00MmQyLTQ4ZTItODQwMi01M2I4OTViNzc4Y2YiLCJzZXNzaW9uX3N0YXRlIjoiYTEyYzhkY2ItMjk5Yy00Y2VlLWEyYWQtOThkN2M1MDJkMDgzIiwiYWNyIjoiMSIsImFsbG93ZWQtb3JpZ2lucyI6WyIqIl0sInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJlYXI tcm9sZTEiXX0sInJlc291cmNlX2FjY2VzcyI6eyJlYXItYmFja2VuZCI6eyJyb2xlcyI6WyJmZWF0dXJlMiIsImZlYXR1cmUxIl19fSwic2NvcGUiOiJvcGVuaWQgZW1haWwgcHJvZmlsZSIsInNpZCI6ImExMmM4ZGNiLTI5OWMtNGNlZS1hMmFkLTk4ZDdjNTAyZDA4MyIsImVtYWlsX3ZlcmlmaWVkIjp0cnV lLCJuYW1lIjoiVXNlciAxMiIsInByZWZlcnJlZF91c2VybmFtZSI6InVzZXIxMiIsImdpdmVuX25hbWUiOiJVc2VyIiwiZmFtaWx5X25hbWUiOiIxMiIsImVtYWlsIjoidXNlci4xMkBhY21lLmNvbSJ9.U8YRbUuOdSPKfDeUIfAb5r12ZGhaTB-GCspY9RjKW8iMn2btbTDd9v9TQAvFbvgHHQ7F0QOtwZvfgW DludO1H3pUiEuhzkRcrw7NQLN4WY3atUrIEACpMa5pthZXzDzia3VBYlChMZPnsMOCAq5-fhULhjYz-4SY6YrTpL5TcDcCuAj28-CZt00hqxGQvd2q-LCpRuFXQ6GnxV0fYJZVtX_yolTAJAVHph7uG_WxgBqpxqdh9QBQ1av3Jn9yElo9qZjzbaD261WR1sae6idkSdLmZai1c7r9zVl9MDw8_qE8tzuaY20gIOG2HpUS4sqW7oM9I5cwMBKCHOzODpXkZg'
And, finally, here is the keycloak config export (very lengthy, unfortunately, but I do not know which parts can be safely deleted). It can be downloaded from my Google Drive, since the file would exceed the maxmimum post length: https://drive.google.com/file/d/1vlZC5-W3AOElsTU12p7NldFmFZSGABkA/view?usp=share_link
Thank you for any hints.

How to get API call origin in NextJS API endpoint

I have an API set up that receives a token, and I want to store that token in a database. But I also want to store the origin URL.
Let's say my API endpoint is located at https://myapp.com/api/connect
Now, I want to send a token from my website https://mywebsite.net
After I send a token, I want to be able to store the token and the website URL to the database in NextJS code.
My endpoint would store this info to the database:
{
token: someRandomToken
origin: https://mywebsite.net
}
I tried logging the whole req object from the handler to see if that info exist but the console log fills my terminal fast.
Inside Next's Server-Side environment you have access to req.headers.host as well as other headers set by Vercel's or other platforms' Reverse Proxies to tell the actual origin of the request, like this:
/pages/api/some-api-route.ts:
import { NextApiRequest } from "next";
const LOCAL_HOST_ADDRESS = "localhost:3000";
export default async function handler(req: NextApiRequest) {
let host = req.headers?.host || LOCAL_HOST_ADDRESS;
let protocol = /^localhost(:\d+)?$/.test(host) ? "http:" : "https:";
// If server sits behind reverse proxy/load balancer, get the "actual" host ...
if (
req.headers["x-forwarded-host"] &&
typeof req.headers["x-forwarded-host"] === "string"
) {
host = req.headers["x-forwarded-host"];
}
// ... and protocol:
if (
req.headers["x-forwarded-proto"] &&
typeof req.headers["x-forwarded-proto"] === "string"
) {
protocol = `${req.headers["x-forwarded-proto"]}:`;
}
let someRandomToken;
const yourTokenPayload = {
token: someRandomToken,
origin: protocol + "//" + host, // e.g. http://localhost:3000 or https://mywebsite.net
};
// [...]
}
Using Typescript is really helpful when digging for properties as in this case. I couldn't tell if you are using Typescript, but in case you don't, you'll have to remove NextApiRequest.

Azure Search API throws CORS error even when CORS is enabled

I have an Azure search index called users that has CORS configured to * (for now) to allow all origins. When I make a GET request to it programmatically using fetch or axios, I get a CORS error:
Access to XMLHttpRequest at 'https://MY_SEARCH_SERVICE.search.windows.net/indexes/users/docs?api-version=2021-04-30-Preview&%24top=5&search=matt*&%24searchFields=name&%24select=id%2Cname%2Cemail&api-key=MY_API_KEY' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
However, if I put the same GET URL into a browser, it returns the list of expected results with no errors.
Here's my code (to run, create a Svelte app and put this in App.svelte or use the Svelte REPL. You must also have an Azure Search service set up, and you'll need to replace the placeholder variables MY_SEARCH_SERVICE and MY_API_KEY with your own, along with an index on which you want to try this):
<script lang="ts">
import { onMount } from "svelte";
const service = "https://MY_SEARCH_SERVICE.search.windows.net";
const index = "users";
const endpoint = `${service}/indexes/${index}/docs`;
const params = new URLSearchParams({
"api-version": "2021-04-30-Preview",
"api-key": "MY_API_KEY",
"$top": "5",
"$searchFields": "name,email",
"$select": "id,name,email"
});
const headers = new Headers({
"accept": "application/json"
});
onMount(async () => {
console.log(`${endpoint}?${params}`);
const response = await fetch(`${endpoint}?${params}`, {
headers: headers
});
console.log(await response.json());
});
</script>

webRTC connection working when connecting to webpage hosted locally, but not when hosted on a server

I am attempting to create a webRTC connection from a python app to a web service using aiortc on python side, and express js on the web service side. When hosting the web service on localhost I have no problems, however when I host it on a server I am unable. I can still access the web page just fine when hosted online, I just get the following very generic exception when I attempt to make a webRTC connection:
socketio.exceptions.ConnectionError: Connection refused by the server.
Here is what I think is the relevant part of the python code:
import asyncio
import dataclasses
import os
import socketio
from pathlib import Path
from aiortc import RTCPeerConnection, RTCSessionDescription
from data_streams.StreamingTrack import StreamingTrack
# Socket.io details
NODEJS_URL = 'something.something.nl'
NODEJS_PORT = '4000'
ROOT = os.path.dirname(__file__)
CLASSROOM_ID = "defaultClassroom"
sio = socketio.AsyncClient()
await sio.connect("http://" + NODEJS_URL + ":" + NODEJS_PORT)
And here is what I believe is the relevant js code:
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const app = express();
app.options('*', cors());
app.set('port', (process.env.PORT || 8080));
// initiating the socket server
const port = 4000;
const server = http.createServer(app);
const io = require('socket.io')(server);
app.use(express.static(__dirname + '/public'));
io.sockets.on('error', (e) => console.log(e));
io.sockets.on('connect_error', (err) => {
console.log(`connect_error due to ${err.message}`);
});
If any additional code is needed I can provide it.
The firewalls have been disabled so I don't think that is the issue, I would greatly appreciate any suggestions as to why I am unable to connect.

No response from Express + postman

I cannot seem to POST data via Postman & Express.
My POST verb code is as follows
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
var fdbRouter = express.Router();
fdbRouter.route('/films')
//post verb
.post(function (req, res) {
var item = new Film(req.body);
console.log(item);
//item.save();
res.status(201).send(item);
})
And my Postman setup is as follows
I have befriended google and came up with this
1. Node.js/Express form post req.body not working
2. req.body empty on posts
3. Express + Postman, req.body is empty
4. `express` app - not able to test the `post` request using `postman`
PS The watched item in postman is default in the mongoose schema i have so it's created regardless whether express works or not.
Whenever I have worked with a post request in express it's been formatted as below (assuming you're using mongoDB):
var express = require('express');
var fdbRouter = express.Router();
var model = require("<FILE TO IMPORT MODEL>") //This file will differ, but you need to import the model you created for films in your DB
var FilmModel = model.Film //also depends on how you exported your model in your dbFiles. Either way you need this model as the blue print for your post request
//I'm also assuming here that you're calling /films correctly and have it sourced as such in your app.js so you don't need /api/films as you have listed in your postman setup image
fdbRouter.post('/films', function(req,res){
var newfilm = new FilmModel()
newFilm.title = req.body.Title
newFilm.year = req.body.Year
newFilm.genre = req.body.Genre
newFilm.save(function(err, savedObject){
if(err){
console.log(err)
res.status(500).send()
}else{
res.send(savedObject)
}
})
})
Please note: this code example assumes a test db with a schema and model has been setup and is available for import to your routes file.
Let me know if this puts you on the right track!