Next.js 13 : Basic middleware example compilation fails with "Class extends value undefined is not a constructor or null" - next.js13

Setup :
On Windows, I created a basic tutorial app in Next.js immediately after installing Next.js 13.
To do so, I used create-next-app and chose Typescript, plus the /src folder.
Under the pages folder, I've added a /cars/cars.ts file. It displays some Hello world text.
I run the project in Visual Studio with a launch.json file that was added on my behalf by VSCode itself (I requested to have the "Next.js: Debug server-side" config).
Everything runs as expected.
Now I'm trying to add a middleware.
I created file middleware.ts in the same folder as the pages folder.
Inside, I copied-pasted the code from the Next.js manual :
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
// Clone the request headers and set a new header `x-version`
const requestHeaders = new Headers(request.headers);
requestHeaders.set('x-version', '13');
// You can also set request headers in NextResponse.rewrite
const response = NextResponse.next({
request: {
// New request headers
headers: requestHeaders,
},
});
// Set a new response header `x-version`
response.headers.set('x-version', '13');
return response;
}
Then I run the project.
Problem :
The project compiles properly when I hit F5.
But then the first time I hit the page, its compilation fails :
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
event - compiled client and server successfully in 1920 ms (165 modules)
wait - compiling /src/middleware (client and server)...
event - compiled successfully in 303 ms (66 modules)
error - Error [TypeError]: Class extends value undefined is not a constructor or null
at ../../node_modules/.pnpm/undici#5.11.0/node_modules/undici/lib/fetch/file.js (evalmachine.<anonymous>:5724:19)
at __require (evalmachine.<anonymous>:14:50)
at ../../node_modules/.pnpm/undici#5.11.0/node_modules/undici/lib/fetch/formdata.js (evalmachine.<anonymous>:5881:49)
at __require (evalmachine.<anonymous>:14:50)
at ../../node_modules/.pnpm/undici#5.11.0/node_modules/undici/lib/fetch/body.js (evalmachine.<anonymous>:6094:35)
at __require (evalmachine.<anonymous>:14:50)
at ../../node_modules/.pnpm/undici#5.11.0/node_modules/undici/lib/fetch/response.js (evalmachine.<anonymous>:6510:49)
at __require (evalmachine.<anonymous>:14:50)
at <unknown> (evalmachine.<anonymous>:11635:30)
at requireFn (file://C:\Users\MathieuBergounioux\source\repos\Next.js\mynext\node_modules\next\dist\compiled\edge-runtime\index.js:1:7079) {
middleware: true
}
wait - compiling /_error (client and server)...
event - compiled client and server successfully in 206 ms (166 modules)
error - Error [TypeError]: Class extends value undefined is not a constructor or null
at ../../node_modules/.pnpm/undici#5.11.0/node_modules/undici/lib/fetch/file.js (evalmachine.<anonymous>:5724:19)
at __require (evalmachine.<anonymous>:14:50)
at ../../node_modules/.pnpm/undici#5.11.0/node_modules/undici/lib/fetch/formdata.js (evalmachine.<anonymous>:5881:49)
at __require (evalmachine.<anonymous>:14:50)
at ../../node_modules/.pnpm/undici#5.11.0/node_modules/undici/lib/fetch/body.js (evalmachine.<anonymous>:6094:35)
at __require (evalmachine.<anonymous>:14:50)
at ../../node_modules/.pnpm/undici#5.11.0/node_modules/undici/lib/fetch/response.js (evalmachine.<anonymous>:6510:49)
at __require (evalmachine.<anonymous>:14:50)
at <unknown> (evalmachine.<anonymous>:11635:30)
at requireFn (file://C:\Users\MathieuBergounioux\source\repos\Next.js\mynext\node_modules\next\dist\compiled\edge-runtime\index.js:1:7079) {
middleware: true
}
Troubleshooting:
I've upgraded everything with this command but it didn't help :
npm i next#latest react#latest react-dom#latest eslint-config-next#latest

Related

socketio-jwt error in building typescript when importing library [Cannot find namespace 'SocketIO'.]

hello guys I am working on a nestjs#v9 that has a chat functionality and I want to be able to authorize the tokens sent by the user while creating the websocket
the app has a build script "build":"npm run remove-build && tsc -p tsconfig.build.json"
when running this script using yarn build
it gives me the error
yarn run build stdout:
$ npm run remove-build && tsc -p tsconfig.build.json
> remove-build
> rm -rf dist
../../node_modules/socketio-jwt/types/index.d.ts(26,14): error TS2503: Cannot find namespace 'SocketIO'.
../../node_modules/socketio-jwt/types/index.d.ts(63,38): error TS2503: Cannot find namespace 'SocketIO'.
I found that if I remove this line
// import { authorize } from 'socketio-jwt';
the error disappears but unfortunately I need to use this authorize method
so my question how can I solve this Issue.
[NOTE] i have this packages inside my package.json
"socket.io": "^4.5.2",
"socket.io-redis": "^6.1.1",
"socketio-jwt": "^4.6.2",
the client should be connecting using this code
const socket = io('http://localhost:1080', {
transports: ['websocket'],
query: {
token: TOKEN,
},
});
the server should authorize the socket using
import { authorize } from 'socketio-jwt';
public createIOServer(port: number, options?: ServerOptions): any {...
const server = super.createIOServer(port, options);
server.adapter(this.redisAdapter);
server.use(
authorize({
decodedPropertyName: 'token',
handshake: true,
secret: secret,
}) as any,
);

jHipster Undertow request failed HttpServerExchange

i'm using jHipster for back-end admin dashboard application and i'm getting this error often that brings my server down every time it appears.
2019-12-26 10:30:29,516 ERROR [XNIO-2 task-10] WebsocketConfiguration$2: Handshake failed due to invalid Upgrade header: null
2019-12-26 10:38:46,039 ERROR [XNIO-2 I/O-1] request: UT005071: Undertow request failed HttpServerExchange{ CONNECT check.best-proxies.ru:80 request {Host=[check.best-proxies.ru:80]} response {}}
java.lang.IllegalArgumentException: UT000068: Servlet path match failed
at io.undertow.servlet.handlers.ServletPathMatchesData.getServletHandlerByPath(ServletPathMatchesData.java:83)
at io.undertow.servlet.handlers.ServletPathMatches.getServletHandlerByPath(ServletPathMatches.java:88)
at io.undertow.servlet.handlers.ServletInitialHandler.handleRequest(ServletInitialHandler.java:151)
at io.undertow.server.handlers.HttpContinueReadHandler.handleRequest(HttpContinueReadHandler.java:65)
at io.undertow.server.handlers.encoding.EncodingHandler.handleRequest(EncodingHandler.java:66)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:336)
at io.undertow.server.protocol.http.HttpReadListener.handleEventWithNoRunningRequest(HttpReadListener.java:255)
at io.undertow.server.protocol.http.HttpReadListener.handleEvent(HttpReadListener.java:136)
at io.undertow.server.protocol.http.HttpReadListener.handleEvent(HttpReadListener.java:59)
at org.xnio.ChannelListeners.invokeChannelListener(ChannelListeners.java:92)
at org.xnio.conduits.ReadReadyHandler$ChannelListenerHandler.readReady(ReadReadyHandler.java:66)
at org.xnio.nio.NioSocketConduit.handleReady(NioSocketConduit.java:88)
at org.xnio.nio.WorkerThread.run(WorkerThread.java:561)
Since jHipster generates a lot of configuration, the only thing i could find about undertow is this method :
#Override
public void customize(ConfigurableEmbeddedServletContainer container) {
MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
// IE issue, see https://github.com/jhipster/generator-jhipster/pull/711
mappings.add("html", MediaType.TEXT_HTML_VALUE + ";charset=utf-8");
// CloudFoundry issue, see https://github.com/cloudfoundry/gorouter/issues/64
mappings.add("json", MediaType.TEXT_HTML_VALUE + ";charset=utf-8");
container.setMimeMappings(mappings);
// When running in an IDE or with ./mvnw spring-boot:run, set location of the static web assets.
setLocationForStaticAssets(container);
/*
* Enable HTTP/2 for Undertow - https://twitter.com/ankinson/status/829256167700492288
* HTTP/2 requires HTTPS, so HTTP requests will fallback to HTTP/1.1.
* See the JHipsterProperties class and your application-*.yml configuration files
* for more information.
*/
if (jHipsterProperties.getHttp().getVersion().equals(JHipsterProperties.Http.Version.V_2_0) &&
container instanceof UndertowEmbeddedServletContainerFactory) {
((UndertowEmbeddedServletContainerFactory) container)
.addBuilderCustomizers(builder ->
builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true));
}
}
Can anyone tell me where is the problem?
Thanks in advance!
It's the search crawler to get url not found,throw the error,you can write robots.txt to prohibit it on the root directory.

App running in Android Emulator fails to perform an HTTP Post to localhost

I'm unable to perform an HTTP Post with an app running in an Android Emulator.
{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content:
System.Net.Http.HttpConnection+HttpConnectionResponseContent, Headers:
{ Server: Microsoft-HTTPAPI/2.0 Date: Wed, 23 Oct 2019 00:58:01
GMT Connection: close Forwarded: host=XXX.XXX.X.XX:XXXXX;
proto=https Content-Type: text/html; charset=us-ascii
Content-Length: 374 }}
Setup:
I'm using an IP address generated by Conveyor by Keyoti
I installed a security certificate on the emulator required by Conveyor by Keyoti
I swapped out Microsoft.AspNetCore.Mvc.HttpPost attribute with System.Web.Http.HttpPost
Emulator:
Successful: HTTP Get
Failed: HTTP Post
Integration Test:
Successful: HTTP Post (using same endpoint)
Code:
I wrote an automated test that calls the same HTTP Post implementation.
Because I executed the same code successfully on my laptop via an automated test, I don't think the actual code is the issue:
open Microsoft.AspNetCore.Mvc
open Newtonsoft.Json
[<ApiController>]
[<Route("api/[controller]")>]
type RegisterController () =
inherit ControllerBase()
[<System.Web.Http.HttpPost>]
member x.Post([<FromBody>] json:string) =
...
Summary:
In conclusion, I have isolated the environment to the Android Emulator and not my laptop. Hence, the emulator can successfully trigger an HTTP Get. However, it fails to perform a HTTP Post even though my laptop device can do both.
UPDATE:
I applied guidance from this Xamarin Android ASP.Net Core WebAPI document.
Specifically, I installed another security certificate on the Android emulator.
I was then able to observe an HTTP Get on the Android Emulator.
However, I continue to get an error for HTTP Post.
OperationCanceledException
Physical Device:
If I run the app from a physical android device I observe the following:
{StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.HttpConnection+HttpConnectionResponseContent, Headers:
{
Date: Wed, 23 Oct 2019 13:33:20 GMT
Server: Kestrel
Transfer-Encoding: chunked
Forwarded: host=xxx.xxx.x.xx:xxxxx; proto=https
Content-Type: text/plain
}}
New Update:
I disabled debugging on just my code on the server implementation and discovered the following exception:
Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: 'Bad chunk size data.'
Any suggestions?
this might not be a direct answer to your question, but i would like to suggest
localtunnel. a very easy way to temporarily expose your local api so that you can test it either on emulator or even physical device. Have used this alot my self, as it is very convenient to just type a single line in terminal to start it.
The following reference solved my issue.
Infrastructure:
type GlobalHttpClient private () =
static let mutable (httpClient:System.Net.Http.HttpClient) = null
static member val Instance = httpClient with get,set
Xamarin.Android project:
using Android.Http;
using Android.Net;
using Javax.Net.Ssl;
using System.Net.Http;
using Xamarin.Android.Net;
using Xamarin.Forms;
using WebGatewaySupport;
[assembly: Dependency(typeof(HTTPClientHandlerCreationService_Android))]
namespace Android.Http
{
public class HTTPClientHandlerCreationService_Android : IHTTPClientHandlerCreationService
{
public HttpClientHandler GetInsecureHandler()
{
return new IgnoreSSLClientHandler();
}
}
internal class IgnoreSSLClientHandler : AndroidClientHandler
{
protected override SSLSocketFactory ConfigureCustomSSLSocketFactory(HttpsURLConnection connection)
{
return SSLCertificateSocketFactory.GetInsecure(1000, null);
}
protected override IHostnameVerifier GetSSLHostnameVerifier(HttpsURLConnection connection)
{
return new IgnoreSSLHostnameVerifier();
}
}
internal class IgnoreSSLHostnameVerifier : Java.Lang.Object, IHostnameVerifier
{
public bool Verify(string hostname, ISSLSession session)
{
return true;
}
}
}
Xamarin.Forms App:
switch (Device.RuntimePlatform)
{
case Device.Android:
GlobalHttpClient.Instance = new HttpClient(DependencyService.Get<IHTTPClientHandlerCreationService>().GetInsecureHandler());
break;
default:
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
GlobalHttpClient.Instance = new HttpClient(new HttpClientHandler());
break;
}
Client Gateway:
let postTo (baseAddress:string) (resource:string) (payload:Object) =
GlobalHttpClient.Instance.BaseAddress <- Uri(baseAddress)
let encoded = Uri.EscapeUriString(resource)
let result = GlobalHttpClient.Instance.PostAsJsonAsync(encoded, payload) |> toResult
result
Looks like you have a .NET Core Api. .NET Core does not have System.Web in Asp.NET. The HttpPost attribute and HttpGet attributes should come from Microsoft.AspNetCore.Mvc namespace which you have open.
Also since you are using the ApiController attribute model binding will just work as long as you bind to a model and not just a json string.
Create a model that you want the json to bind to and use that type for your parameter on Post and remove the FromBody attribute. Also if you do that you probably don't need newtonsoft.json.
open Microsoft.AspNetCore.Mvc
[<ApiController>]
[<Route("api/[controller]")>]
type RegisterController () =
inherit ControllerBase()
[<HttpPost>]
member x.Post(thing:TypeOfThing) =

Shopware installation error: Identifier DB not initialized yet

After installation wizard is finished I get this error.
Slim Application Error
The application could not run because of the following error:
Details
Type: RuntimeException
Message: Identifier DB not initialized yet
File: /.../recovery/install/src/ContainerProvider.php
Line: 162
Is there is some configuration file where I can set DB params? I had insert all params via installation wizard.
In file recovery/install/src/ContainerProvider.php
Add 2 strings:
In use-section
use Shopware\Recovery\Update\Utils;
2.Inside the register-function:
$container['db'] = function ($c) {
$conn = Utils::getConnection(SW_PATH);
return $conn;
};

Ionic: Error: Module build failed: Error: ENOENT: no such file or directory

I am using Ionic, and get the following error:
Runtime Error Uncaught (in promise): Error: Module build failed:
Error: ENOENT: no such file or directory, open
'/Users/richardmarais/Development/ionic/theWhoZoo/src/pages/model/ratingModel.js'
The error is a result of this line of code:
this.ratingModel = new RatingModel();
When I remove this line, I don't get the error.
ratingModel.ts
import { Injectable } from "#angular/core";
import { PersonModel } from './personModel';
import { JobModel } from './jobModel';
#Injectable()
export class RatingModel {
public id: number = null;
public job: JobModel = null;
public review: string = null;
public rating: number = null;
public reviewDate: number = null;
public time: string = null;
public person: PersonModel = null;
public anonymous: number = null;
constructor() {
}
}
Reading other forums, people are getting this error due to the case not matching in their imports, but I have checked mine, and they do match.
import { RatingModel } from '../model/ratingModel';
However, I have noticed something strange in my IDE (Visual Studio Code):
As you can see, in the search results, there are two files for the object, ratingModel.ts and RatingModel.ts. But when I check the actual files system, there is only on file, ratingModel.ts:
Question
Does anyone know what and how to resolve what looks like possibly a bug or fault here?
Thanks
More info:
global packages:
#ionic/cli-utils : 1.0.0
Cordova CLI : 6.4.0
Ionic CLI : 3.0.0
local packages:
#ionic/app-scripts : 1.3.0
#ionic/cli-plugin-cordova : 1.0.0
#ionic/cli-plugin-ionic-angular : 1.0.0
Ionic Framework : ionic-angular 3.2.1
System:
Node : v7.10.0
OS : macOS Sierra
Xcode : Xcode 8.3.2 Build version 8E2002
ios-deploy : not installed
ios-sim : not installed
Apologies, my bad. I just found another file that was importing the object with the incorrect case. It does appear as if there is no issue, and I had a bug in my code.
import { RatingModel } from '../model/RatingModel';
This error occurred when your component can't be found with your app.module settings.
Follow these steps to solve your problem:
Right click on your web browser and select inspect (in this case I use chrome)
In the source tab, navigate to localhost:8100 (the default port for running ionic)
Go to src -> pages and open corresponded page(in this case 'model')
The name of .ts file and path must be as same as the name and path of the added import path in app.module.ts
In this case, there isn't model/ratingModel.ts
be aware :
The path is case sensitive (maybe the .ts file is RatingModel)

Resources