Passing JSON data in Express Middleware
I have the following route in my express app:
app.post("/users/me/trackers/court_cases", caseValidator, DriversController.court_cases);
I would like to be able to pass information from my second middleware, caseValidator, to the third set of middleware. The second middleware currently fetches JSON data from a RESTful API, that I would like to pass along to the final route before sending it to the user.
Here's my current case validator function:
caseValidator = function(req, res, next){
var case_id = req.body.case_id;
var authOptions = {
method: 'GET',
url: `https://www.courtlistener.com/api/rest/v3/dockets/${case_id}/`,
headers: {
'Authorization' : "myauth"
},
json: true
};
var url = `https://www.courtlistener.com/api/rest/v3/dockets/${case_id}/`
axios(authOptions)
.then((response) => {
console.log("success!")
next();
//// Pass in the JSON data to the next middleware?
})
.catch((error) => {
res.status(400)
.send(error)
});
};
1 answer
-
answered 2018-07-11 05:12
Majid Sajadi
you can use
req.someVar
.axios(authOptions) .then(response => { console.log("success!"); req.someVar = response.data; next(); })
then in next middleware you have access to that data.
See also questions close to this topic
-
OAuth with Passport.js in a multi tenant application
I am working on a website that will allow multiple tenants using subdomains.
Accounts will be able to add their own subdomains, as long as they don't already exist; eg:
http://tenant1domain1.mywebsite.com http://tenant1domain2.mywebsite.com http://tenant2domain1.mywebsite.com http://tenant2domain2.mywebsite.com
I am also adding in the ability to sign in using a number of oauth providers (google, microsoft, azure ad etc) using passport.js.
All these services will all callback to the main domain (mywebsite.com/login/google/callback) and I need to identify the subdomain of the login request to redirect the user.
As a single user can have multiple subdomains, I can't easily store this against their user record.
I'm running into a problem at the moment where I can't find a way to persist the tenant information past the passport authenticate stage.
I tried using session variables but the session is reset at the callback stage and loses any information I've stored there.
I did think about adding the subdomains as allowed callback urls against each service then just setting the callback to the subdomain but this quickly becomes unmanageable.
Is there any way to make passport.js keep existing session variables intact or to use another method to transfer the tenant information?
-
React - Infinite looping xhr sockjs-node
I have never hosted a website using react.js (Create-React-App).
I have made this website online but I have not turned on the API.
i don't know why i get auto looping xhr socketjs-nodes like this:
and even though I only entered 1 project using React.js and got Physical Memory Usage almost 600MB is this all because of this xhr?
here is my package.json :
{ "name": "client", "version": "0.1.0", "private": true, "dependencies": { "@fortawesome/fontawesome-svg-core": "^1.2.12", "@fortawesome/free-brands-svg-icons": "^5.6.3", "@fortawesome/free-solid-svg-icons": "^5.6.3", "@fortawesome/react-fontawesome": "^0.1.3", "@material-ui/core": "^3.7.1", "@material-ui/icons": "^3.0.1", "axios": "^0.18.0", "forever": "^0.15.3", "history": "^4.7.2", "js-cookie": "^2.2.0", "jsonwebtoken": "^8.4.0", "jwt-decode": "^2.2.0", "moment": "^2.23.0", "prop-types": "^15.6.2", "querystring": "^0.2.0", "react": "^16.7.0", "react-addons-update": "^15.6.2", "react-cookie": "^3.0.8", "react-dom": "^16.7.0", "react-image-gallery": "^0.8.12", "react-images": "^0.5.19", "react-redux": "^6.0.0", "react-router-dom": "^4.3.1", "react-scripts": "2.1.2", "react-select": "^2.3.0", "react-slick": "^0.23.2", "redux": "^4.0.1", "redux-devtools-extension": "^2.13.7", "redux-thunk": "^2.3.0", "slick-carousel": "^1.8.1", "typeface-roboto": "0.0.54" }, "scripts": { "start": "PORT=40000 react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": "react-app" }, "browserslist": [ ">0.2%", "not dead", "not ie <= 11", "not op_mini all" ] }
-
GraphQL relationship returning null
I'm learning graphql and working on a simple API with mongodb database. I can't figure out why the relationship declared in my schema is not working :
type People { id:ID! firstName:String! lastName:String! email:String! serviceId:String apps:[String] service:Service } type Service { id:ID! name:String! location:String! peoples:[People] }
When I run this query:
query getLocationByPerson { People { firstName lastName service { location } } }
Here's what I get:
"People": [ { "firstName": "John", "lastName": "DOE", "service": null }, { "firstName": "Jane", "lastName": "DOE", "service": null } ]
Any idea of what I'm missing here?
-
Axios post doesn't receive answer (ReactJS)
I need to submit a form. It currently works if I do it in the HTML form, but I really need to make some stuff after so I need to do it in react. So I'm using axios.
However, using axios I don't get a response back. Also there's something strange, because although I'm doing a post request, the data appears as a query string on the browser... Not sure if that's the normal behaviour.
Here's my code, on the server side:
app.post("/auth/register", async function(req, res, next) { // some code // my responses are like res.json("/signup/success"); }
on the client side:
onSubmit(event) { axios({ method: "post", url: "/auth/register", data: { username: this.state.username, password: this.state.password, accountName: this.state.accountName }, withCredentials: true }).then(result => { console.log(result); }); }
I'm running a server on port 5000 using express, and I used create-react-app to run a server on port 3000. To manage authentication, passport.js.
I use http-proxy-middleware to proxy some endpoints to the express server.
After submitting the form I get this on the console:
I've been at this for days, wandering around stackoverflow and everywhere else, and I'm completely stuck... Can anyone please give me a hint on what can I do?
-
How do you do server side processing in a React app?
I'm writing my first Node/React/Express/Next app.
I'm uncertain how to execute server side code when a request comes in.
When there's a request, I need to get some data off the server disk. I'm trying to do this from a javascript file in my pages directory, but the 'fs' module is not accessible from here. I guess that's because the browser must be executing the code (which is confusing for me because I thought next.js meant the server was processing the code and exporting the html back).
I've done much googling about this problem and can't seem to find an answer. Which is bizarre, because this must be one of the most basic requirements of a web app. Maybe the solution is so basic and I'm just overlooking the obvious?
Can anyone provide a brief explanation or pointers in the right direction on how to do server-side processing (eg reading a file from the servers disk) from a /pages/xxx.js file in a React/Express/Next app? Or in other words, how or where do I access the 'fs' module?
The error I get is "ModuleNotFoundError: Module not found: Error: Can't resolve 'fs' in /pages
thanks
-
I can't connect to database server
I got this error while I was trying to access database server,
"cdr_mysql.c:203 mysql_log: Cannot connect to database server localhost: (2002) Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)"
What are the possible reasons that have triggered this error ?
-
SQL Time Zone Issue
I am working on a project based on PHP i have an issue that i purchased a hosting whose server is of another country and i am in Pakistan when i enter data in database table from PHPMyAdmin in enters the date of that country which is 11 hours behind us that's why my insert queries and update queries not working Php time zone is set but server time zone is not set.
php_value date.timezone 'Asia/Karachi';
i use this is my htaccess file Also use
date.timezone = "Asia/Karachi"
in php ini file
-
TCP socket timeout
I wrote C# program that server sends data from Server to Client only. Problem is that time between it sends data is changable ( max 5min) and that causes sometimes connection to timeout.
When I send data every 3sec then none of them timeouts. But if message send after 5min then there is problem on Client to recieve it.
I made timeout feature that both Client and Server has. After timeout every reconnects:
public class TimerControl { private System.Timers.Timer timeoutTimer = null; public void initTimeout(int timeMS, System.Timers.ElapsedEventHandler funct) { timeoutTimer = new System.Timers.Timer(); timeoutTimer.Interval = timeMS; //MS timeoutTimer.Elapsed += funct; timeoutTimer.AutoReset = true; setTimeoutTimer(false); } public void setTimeoutTimer(bool state) { if (timeoutTimer != null) { timeoutTimer.Stop(); timeoutTimer.Enabled = state; if (state) timeoutTimer.Start(); } } public void resetTimeoutTimer() { if (timeoutTimer != null && timeoutTimer.Enabled) { timeoutTimer.Stop(); timeoutTimer.Start(); } } }
that has not solved the trouble.
What should I do to make it work correct and not timeout after some time?
Server:
public class TCPserver :TCPunit { private int TIMEOUT_MS = 5000; Socket serverListener = null; Queue<string> dataQueued = null; bool isConnectedForced = false; public TCPserver() { dataQueued = new Queue<string>(); initTimeout(TIMEOUT_MS, reconnect); } public void sendDataToClient(string message) { dataQueued.Enqueue(message + Environment.NewLine); if(isConnectedForced) startListening(); if (dataQueued.Count > 0) setTimeoutTimer(true); } public bool connect(string adress) { this.thisUnitAdress = adress; isConnectedForced = true; loopedConnect(); startListening(); return true; } public bool disconnect() { isConnectedForced = false; loopedDisconnect(); return true; } private bool loopedConnect() { try { IPAddress ipAddress = IPAddress.Parse(this.thisUnitAdress); IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port); if (serverListener != null) loopedDisconnect(); serverListener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); serverListener.Bind(localEndPoint); Console.WriteLine("SERVER connected to: " + this.thisUnitAdress + " port : " + port.ToString()); return true; } catch (Exception ex) { Console.WriteLine("!!! SERVER connect"); setTimeoutTimer(true); return false; } } private bool loopedDisconnect() { setTimeoutTimer(false); if (serverListener != null) { if (serverListener.Connected) serverListener.Shutdown(SocketShutdown.Both); serverListener.Close(); Console.WriteLine("SERVER CLOSED!"); serverListener = null; } return true; } private void reconnect(Object source, System.Timers.ElapsedEventArgs e) { if (isConnectedForced) { Console.WriteLine("SERVER RECONNECT!!!"); loopedDisconnect(); loopedConnect(); if (dataQueued.Count > 0) setTimeoutTimer(true); else setTimeoutTimer(false); } else { setTimeoutTimer(false); } } private void startListening() { try { serverListener.Listen(100); Console.WriteLine("SERVER Waiting for a connection..."); serverListener.BeginAccept(new AsyncCallback(AcceptCallback), serverListener); setTimeoutTimer(true); } catch (Exception ex) { Console.WriteLine("!!! SERVER sendingLOOP"); setTimeoutTimer(true); } } private void AcceptCallback(IAsyncResult ar) { try { Socket listener = (Socket)ar.AsyncState; Socket handler = listener.EndAccept(ar); //HERE SEND while (dataQueued.Count > 0) { string data = dataQueued.Dequeue(); byte[] byteData = Encoding.ASCII.GetBytes(data); handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler); } //handler.Shutdown(SocketShutdown.Both); //handler.Close(); setTimeoutTimer(false); } catch (Exception ex) { Console.WriteLine("!!! SERVER AcceptCallback"); setTimeoutTimer(true); } } private void SendCallback(IAsyncResult ar) { try { ((Socket)ar.AsyncState).EndSend(ar); } catch(Exception ex) { Console.WriteLine("!!! SERVER SendCallback"); setTimeoutTimer(true); } } }
Client:
public class TCPclient : TCPunit { private int TIMEOUT_MS = 5000; Socket client; IPEndPoint remoteEP; bool isConnecting = false; bool isRecieving = false; // TELS IF PROGRAM SHOULD LOOK FOR SERVER ALL TIME Action<string> afterRecieveAction = null ; // To print to GUI public TCPclient() { initTimeout(TIMEOUT_MS, reconnect); } public void assignAfterRecieveAction(Action<string> action) { this.afterRecieveAction = action; } public bool connect(string adress) { thisUnitAdress = adress; loopedConnect(); return true; } public bool disconnect() { isRecieving = false; isConnecting = false; loopedDisconnect(); return true; } private bool loopedConnect() { IPAddress ipAddress = IPAddress.Parse(this.thisUnitAdress); remoteEP = new IPEndPoint(ipAddress, port); client = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); setTimeoutTimer(true); isRecieving = true; StartClientListening(); return true; } private bool loopedDisconnect() { if (client != null) { if (client.Connected) client.Shutdown(SocketShutdown.Both); client.Close(); Console.WriteLine("CLIENT CLOSED!"); client = null; } return true; } private void reconnect(Object source, System.Timers.ElapsedEventArgs e) { if (isRecieving) { Console.WriteLine("CLIENT RECONNECT!!!"); if (isConnecting) loopedDisconnect(); isRecieving = true; loopedConnect(); } } private void StartClientListening() { try { if (isRecieving) { client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback) , client); isConnecting = true; Console.WriteLine("CLIENT listens to: " + thisUnitAdress + " port : " + port.ToString()); } } catch (System.Net.Sockets.SocketException ex) { Console.WriteLine("CLIENT StartClientListening"); } catch (Exception ex) { Console.WriteLine("!!! CLIENT StartClientListening2"); if (isRecieving) setTimeoutTimer(true); } } private void ConnectCallback(IAsyncResult ar) { try { client.EndConnect(ar); Console.WriteLine("CLIENT connected to {0}", client.RemoteEndPoint.ToString()); StateObject state = new StateObject(); state.workSocket = client; client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); ; } catch (Exception e) { Console.WriteLine("!!! CLIENT ConnectCallback"); if (isRecieving) setTimeoutTimer(true); } } private void ReceiveCallback(IAsyncResult ar) { try { StateObject state = (StateObject)ar.AsyncState; Socket client = state.workSocket; int bytesRead = client.EndReceive(ar); if (bytesRead > 0) { String response = Encoding.ASCII.GetString(state.buffer); if (afterRecieveAction != null) afterRecieveAction(response); resetTimeoutTimer(); client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); } } catch(System.Net.Sockets.SocketException ex) { Console.WriteLine("!!! CLIENT ReceiveCallback"); if (isRecieving) setTimeoutTimer(true); } catch(Exception ex) { Console.WriteLine("!!! CLIENT ReceiveCallback2"); if (isRecieving) setTimeoutTimer(true); } } }
How to make async Server-Client to work without timeouts?
Best regards, Chris
-
Route component only loading after page refresh?
After I log in my application and try to change routes, the URL changes but the component doesn't load.
I have tried reordering the routes in different ways but that also doesn't seem to work.
My app-routing module:
const routes: Routes = [ { path: 'settings', canActivateChild: [AuthGuard], children: [ { path: 'manage-labels', component: ManageLabelsComponent, data: { title: 'Manage Labels' } }, { path: 'profile-settings', component: ProfileSettingsComponent, data: { title: 'Profile Settings' } }, { path: '', component: SettingsComponent, data: { title: 'Settings' } } ] }, { path: '', component: HomeComponent, canActivate: [AuthGuard], data: { title: 'Home' }, pathMatch: 'full' }, { path: 'about', component: AboutComponent, data: { title: 'About Us' } }, { path: 'login', component: LoginComponent, data: { title: 'Login' } }, { path: '**', component: NotFoundComponent, data: { title: 'Page Not Found' } } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], providers: [AuthService, AuthGuard] })
I find it weird that it needs to refresh to "load" the routes. Perhaps routes aren't loaded after login?
Edit: Specifically the settings component. I've also tried having it as a single route with not children and that didn't work either.
-
Laravel | Only the / route works with Shared Hosting Web server
I have been struggling with this issue for several days now. I have completed a working Laravel (5.7.22) project and uploaded to a shared hosting server with following folder structure.
- \
- public_html -all files in the local 'public' folder
- app1 - all the other folders in local laravel project folder.
Following are my index.php lines:
require __DIR__.'/../app1/vendor/autoload.php'; $app = require_once __DIR__.'/../lms/bootstrap/app.php'; $app->bind('path.public', function() { return __DIR__;});
below is the .htaccess file:
server.php has following
$uri = urldecode( parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)); if ($uri !== '/' && file_exists(__DIR__. '/public_html'.$uri)) { return false; } require_once __DIR__. '../public_html/index.php';
Then this is my routes file web.php
Route::get('/', function () { return view('auth/login'); }); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home'); Auth::routes(); Route::resource('admin/delivery-client', 'Admin\\DeliveryClientController'); Route::resource('admin/document', 'Admin\\DocumentController'); Route::resource('admin/customer', 'Admin\\customerController');
The issue is only the root url works. i.e. domain name\ then it loads the login page. For all other links and commands it gives following kind error.
Not Found The requested URL /app1/index.php/register was not found on this server. Apache/2.4.37 (Unix) Server at 217.199.187.62 Port 80
When I changed / route view to another eg: home, then Home page loads. Site works perfectly on local server.
-
Angular (v6) recursive routes with same component
I have an application being developed using Angular 6, that uses nested components. The same route can repeat any number of times.
Requirement: Component "Job" can have any number of sub jobs. So I need to be able to navigate to sub job like this: Job 1 > Job 2 > Job 3 ...etc.
Problem: I cannot get the routing to work to be able to get this recursive structure to going.
Routing configuration:
const routes: Routes = [ { path: '', component: LayoutComponent, children: [ { path: 'jobs/:id', data: { breadcrumbs: '{{ job.text }}' }, component: JobComponent, resolve: { job: JobResolver }, children: [ { path: '**', component: JobComponent, resolve: { job: JobResolver }, children: [ { path: '', pathMatch: 'full', component: JobDetailsComponent }, { path: 'folders/:folder_id', data: { breadcrumbs: '{{folder.text}}' }, component: FolderComponent, resolve: { folder: FolderResolver }, children: [ { path: '**', pathMatch: 'full', component: FolderDetailsComponent, } ] } ] } ] } ] } ];
Would it be possible to navigate to http://localhost:4000/home/jobs/1/jobs/2/jobs/3/folders/10/folders/11 ?
-
Laravel | Middleware binding not accessible in controller
I have a middleware which just grabs the sub domain and binds it to the
Store
model.<?php namespace App\Http\Middleware; use Closure; use App\Models\Store; class SubDomain { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @param string|null $guard * @return mixed */ public function handle($request, Closure $next, $guard = null) { $sub_domain = array_first(explode('.', $request->getHost())); app()->bind(Store::class, function () use ($sub_domain) { return Store::query()->where('sub_domain', $sub_domain)->firstOrFail(); }); return $next($request); } }
However, when I am inside of a controller I am trying to extend it so I can always do
$this->store->id
or something alike however, the Store isn't getting found.<?php namespace App\Http\Controllers; use App\Models\Store; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; class Controller extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; /** * @var Store */ protected $store; /** * Controller constructor. * * @param Store $store */ public function __construct(Store $store) { $this->store = $store; } }
The store is always just a basic model with no data.
This is my route:
Route::group(['middleware' => ['auth', 'sub_domain'], 'prefix' => 'admin'], function () { Route::get('/dashboard', 'Admin\DashboardController@index'); });
And I have registered the sub_domain middleware inside of the
Kernel
. -
System.Net.Http.HttpRequestException: Device not configured ---> System.Net.Sockets.SocketException: Device not configured
System.Net.Http.HttpRequestException: Device not configured ---> System.Net.Sockets.SocketException: Device not configured
I'm receiving the above error when trying to make a web request from a custom middleware piece for an aspnet core web application. The error occurs on the fourth line of the following block of code:
var web = new WebClient(); var testing = _configuration.GetSection("IPStack")["AccessKey"]; web.QueryString.Add("access_key", _configuration.GetSection("IPStack")["AccessKey"]); string ipstackRaw = web.DownloadString($"http://api.ipstack/{ipaddress}");
I'm using Visual Studio on Mac, Community Edition. What's causing this error?
-
middleware called even if it should not be called
I do not why this middleware is called even if it shouldn't be.
This is the middleware:
<?php namespace App\Http\Middleware; use ...; class FacebookLogin { public function handle($request, Closure $next) { Session::flash('error', "My message error"); return $next($request); } }
This is my Kernel.php file:
use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel { protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, \App\Http\Middleware\TrimStrings::class, \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, ]; protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, ], 'api' => [ 'throttle:60,1', 'bindings', ], ]; protected $routeMiddleware = [ 'auth' => \Illuminate\Auth\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, 'can' => \Illuminate\Auth\Middleware\Authorize::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'fb.login' => \App\Http\Middleware\FacebookLogin::class, 'cors' => \App\Http\Middleware\Cors::class, 'auth.api' => \App\Http\Middleware\AuthApi::class, 'role' => \Spatie\Permission\Middlewares\RoleMiddleware::class, ]; }
This is my RouteServiceProvider.php file:
namespace App\Providers; use Illuminate\Support\Facades\Route; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider { protected $namespace = 'App\Http\Controllers'; public function boot() { parent::boot(); } public function map() { $this->mapApiRoutes(); $this->mapWebRoutes(); $this->mapFacebookRoutes(); } protected function mapWebRoutes() { Route::middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web.php')); Route::prefix('ajax') ->middleware('web') ->namespace($this->namespace) ->group(base_path('routes/ajax.php')); Route::middleware(['web', 'auth']) ->namespace($this->namespace) ->group(base_path('routes/auth.php')); } protected function mapApiRoutes() { Route::prefix('api') ->middleware('api') ->namespace($this->namespace) ->group(base_path('routes/api.php')); } protected function mapFacebookRoutes() { Route::group([ 'middleware' => ['web', 'fb.login'], 'namespace' => $this->namespace, 'prefix' => 'fb', ], function () { require base_path('routes/facebook.php'); }); Route::group([ 'middleware' => ['web', 'fb.login'], 'namespace' => $this->namespace, 'prefix' => 'fb/ajax', ], function () { require base_path('routes/facebook_ajax.php'); }); } }
What I get is the Flash message shown when I navigate to base url of my site (for example: www.example.com).
But, as you can see in the
mapWebRoutes
function, I apply only the web middleware to the web routes, so I do not whyFacebookLogin
middleware is called.
I apply theFacebookLogin
middleware only to "fb" and "fb/ajax" prefix routes.I noticed another strange behaviour: I get the message only if I visit https version of my website, not if I visit http version.