What could cause a promise to fail in Nativescript angular2? - http

I am trying to Http GET from a database , where I do have access and can reproduce the GET result in Postman.
I have created a service in angular2 {N} where I execute this GET but I get an error of :
JS: EXCEPTION: Error: Uncaught (in promise): Response with status: 200 for URL: null
JS: STACKTRACE:
JS: Error: Uncaught (in promise): Response with status: 200 for URL: null
JS: at resolvePromise (/data/data/org.nativescript.ndemo/files/app/tns_modules/zone.js/dist/zone-node.js:496:32)
JS: at resolvePromise (/data/data/org.nativescript.ndemo/files/app/tns_modules/zone.js/dist/zone-node.js:481:18)
JS: at /data/data/org.nativescript.ndemo/files/app/tns_modules/zone.js/dist/zone-node.js:529:18
JS: at ZoneDelegate.invokeTask (/data/data/org.nativescript.ndemo/files/app/tns_modules/zone.js/dist/zone-node.js:314:38)
JS: at Object.NgZoneImpl.inner.inner.fork.onInvokeTask (/data/data/org.nativescript.ndemo/files/app/tns_modules/#angular/core/src/zone/ng_zone_impl.js:37:41)
JS: at ZoneDelegate.invokeTask (/data/data/org.nativescript.ndemo/files/app/tns_modules/zone.js/dist/zone-node.js:313:43)
JS: at Zone.runTask (/data/data/org.nativescript.ndemo/files/app/tns_modules/zone.js/dist/zone-node.js:214:48)
JS: at drainMicroTaskQueue (/data/data/org.nativescript.ndemo/files/app/tns_modules/zone.js/dist/zone-node.js:432:36)
JS: Unhandled Promise rejection: Response with status: 200 for URL: null ; Zone: angular ; Task: Promise.then ; Value: Response with status: 200 for URL: null
JS: Error: Uncaught
(in promise): Response with status: 200 for URL: null
My service :
import { Headers, Http } from '#angular/http';
import 'rxjs/add/operator/toPromise';
export function createNonJsonResponse(http: Http, fullUrl: string): Promise<string>{
return http.get(fullUrl)
.toPromise()
.then(response => response.text())
// .catch(this.handleError);
}
I have logged both the URL given in and the Http and they are fine.
I have no idea why is this happening and google couldn't help me find any solutions whatsoever.

It seems, at least for me, #angular/core Http module is not working as intended. I switched to the nativescript's Http service (https://docs.nativescript.org/cookbook/http) and managed to accomplish what I needed without any problems.

Are you injecting the service somewhere? Add #Injectable() above the export. What if you change how you write the service a little and see if you receive the same response?
#Injectable()
export class createNonJsonResponse {
fullUrl: string = 'http://httpbin.org/get';
constructor(private http: Http) {}
getNonJsonResponse() {
return this.http.get(this.fullUrl)
.toPromise()
.then(response => response.text())
.catch(this.handleErrors);
}
}
Then import it to your component
import {createNonJsonResponse} from "./yourservicename.service"
And finally call it
this.createNonJsonResponse.getNonJsonResponse().then(function (data) {
alert("here");
//console.log(data);
//console.dump(data);
})
This worked for me I was able to hit my alert.

Related

What is the best practice to bypass my specific dynamic code evaluation in next.js middleware?

I use next.js middleware to retrieve a data stored inside a cookie, and to check in a db (using strapi) if this specific user exists, or if he needs to register before going further.
// middleware.js
import { getToken } from 'next-auth/jwt';
import qs from 'qs';
import { MY_DB } from './constants';
export async function middleware(request) {
const token = await getToken({
req: request,
secret: process.env.SECRET,
});
const params = qs.stringify({
filters: {
address: {
$eq: token.sub,
},
},
});
const url = MY_DB + '/api/users/?' + params;
const result = await fetch(url, {
method: 'GET',
headers: { accept: 'application/json' },
});
// remaining code checks if the request is empty or not and returns the appropriate page
(...)
building my project returns the following error :
Failed to compile.
./node_modules/.pnpm/function-bind#1.1.1/node_modules/function-bind/implementation.js
Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation
Import trace for requested module:
./node_modules/.pnpm/function-bind#1.1.1/node_modules/function-bind/implementation.js
./node_modules/.pnpm/function-bind#1.1.1/node_modules/function-bind/index.js
./node_modules/.pnpm/get-intrinsic#1.1.3/node_modules/get-intrinsic/index.js
./node_modules/.pnpm/side-channel#1.0.4/node_modules/side-channel/index.js
./node_modules/.pnpm/qs#6.11.0/node_modules/qs/lib/stringify.js
./node_modules/.pnpm/qs#6.11.0/node_modules/qs/lib/index.js
> Build failed because of webpack errors
 ELIFECYCLE  Command failed with exit code 1.
I highly suspect the qs.stringify call given the stacktrace, but how can I overcome this in an elegant way ?

Firebase: Cross-origin redirection to (url) denied by Cross-Origin Resource Sharing policy:Status code: 301 [duplicate]

This question already has answers here:
NextJs CORS issue
(10 answers)
Closed 8 months ago.
I am trying to deploy a firebase function and call the function from a nextjs app. The function works when it runs on firebase emulator, and when it is deployed I am able to call the function from postman. However, when deployed and I try to call using fetch I get an error. I have also tried to deploy the website to call from a different url but still get the same error.
Here is the calling function:
export async function getArticle(articleURL) {
const response = await fetch(articleURL);
const json = await response.json();
return json.result;
}
Here is the firebase function that I am trying to call:
const cors = require('cors')({origin: true});
exports.getArticle = functions
.runWith({
timeoutSeconds: 120,
memory: "1GB",
})
.https.onRequest(async (req, response) => {
cors(req, response, async() => {
try {
{code}
response.status(200).json({ result: 'test' });
}
catch (e) {
response.status(400).json({ result: "error", message: e.message });
}finally {
{code}
}
})
});
I have also tried adding headers such as:
response.set('Access-Control-Allow-Origin', "*");
response.set('Access-Control-Allow-Headers', "*");
but nothing seems to work. I have tried for hours but nothing works. The error I get is:
[Error] Cross-origin redirection to (url) denied by Cross-Origin Resource Sharing policy: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. Status code: 301
[Error] Fetch API cannot load (url) due to access control checks.
[Error] Failed to load resource: Cross-origin redirection to (url) denied by Cross-Origin Resource Sharing policy: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. Status code: 301
[Error] Unhandled Promise Rejection: TypeError: Load failed
Lastly, I have also tried adding parameters to my fetch call such as :
fetch(URL, {
mode: 'cors',
headers: {
'Access-Control-Allow-Origin':'*'
}
})
Overall, nothing seems to work and don't know what else to try. Any help would be greatly appreciated.
The problem was not with the firebase function but with the api call on nextjs. I was importing the function and making the call from a component. Instead I found the solution on this post: NextJs CORS issue.
The solution that worked for me was by chispitaos. I changed my getArticle function to the api format and fetched the internal api which then fetched the firebase function. Here was my new function:
export default async function handler(req, res) {
try {
const response = await fetch(`any url`);
const json = await response.json();
console.log(json);
res.status(200).send(json);
} catch (error) {
console.error(error)
return res.status(error.status || 500).end(error.message)
}
}
and here was how I called it :
const newData = await fetch('/api/getArticle');
This fixed the issue for me.

Failed to load static props with empty paths and fallback

I have the following code on my Dynamic Routing page [id] that I am trying to use with next-i18next translations. However, it is throwing an error when being deployed on Vercel (working locally). I am trying to use the fallback function with an empty path array to somehow accept all possible paths(?). In my console I am getting a statuscode 500 GET-error and a "Failed to load static props"-error.
It is working when I specify a specific id within getStaticPaths and go to that matching path. However, I can't possibly specify thousands of ids for this to work. Shouldn't the fallback take care of this or how can I get past this?
export async function getStaticPaths() {
return {
paths: [], fallback: true
}
}
export async function getStaticProps(context) {
return {
props: {
params: context.params,
...(await serverSideTranslations(context.locale, ["common"])),
},
}
}
Update:
This is the Vercel function log (xxxxx-values is some id's I removed)
[GET] /_next/data/xxxxxxxxxxx-y/en/packages/490713.json
20:26:37:98
2022-02-28T19:26:39.300Z xxxxxxxxxxxxxxxxxxxxx ERROR Error: ENOENT: no such file or directory, scandir '/var/task/public/locales/en'
at Object.readdirSync (fs.js:1047:3)
at getLocaleNamespaces (/var/task/node_modules/next-i18next/dist/commonjs/config/createConfig.js:175:23)
at /var/task/node_modules/next-i18next/dist/commonjs/config/createConfig.js:181:20
at Array.map (<anonymous>)
at getNamespaces (/var/task/node_modules/next-i18next/dist/commonjs/config/createConfig.js:180:44)
at createConfig (/var/task/node_modules/next-i18next/dist/commonjs/config/createConfig.js:221:29)
at _callee$ (/var/task/node_modules/next-i18next/dist/commonjs/serverSideTranslations.js:199:53)
at tryCatch (/var/task/node_modules/regenerator-runtime/runtime.js:63:40)
at Generator.invoke [as _invoke] (/var/task/node_modules/regenerator-runtime/runtime.js:294:22)
at Generator.next (/var/task/node_modules/regenerator-runtime/runtime.js:119:21) {
errno: -2,
syscall: 'scandir',
path: '/var/task/public/locales/en',
page: '/packages/[id]'
}
RequestId: xxxxxxxxxxxxxxxxxxxx Error: Runtime exited with error: exit status 1
Runtime.ExitError
This line was missing in my next-i18next-config
localePath: path.resolve('./public/locales'),

Angular2 HTTP service for localhost Web API running on different port

I am getting below error when using HTTP service in angular2 with localhost WEB Api. When using URL directly in browser it is working fine and returning JSON result.
An error occurred Response with status: 404 Not Found for URL: null
import { Headers, Http } from '#angular/http';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class QuizDalService {
private quizquestionUrl = 'http://localhost:59786/api/AngularQuiz';
constructor(private http: Http) { }
getQuizQuestions(name: string): Promise<mcquestion[]>{
return this.http.get(this.quizquestionUrl)
.toPromise()
.then(response => response.json().data as mcquestion[])
.catch(this.handleError);
}
}
Please let me know if I am missing anything.

Angular 2 HTTP GET returning URL null

I am trying to make a simple HTTP GET request using angular 2 with Typescript. I am getting a 404 error, with a null url. Shown below is my component file, and the error I am receiving.
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { BreadcrumbService } from './breadcrumbService';
import { Http, Response } from '#angular/http';
#Component({
moduleId: module.id,
providers: [ BreadcrumbService],
templateUrl: 'html/appList.html',
styleUrls: ['css/list.css']
})
export class HealthComponent {
constructor(private http: Http) {
this.http.get('http://jsonplaceholder.typicode.com/posts/1')
.toPromise()
.then((res: Response) => {
console.log('RES: ', res);
})
.catch((err: Error) => {
console.log('ERR!!: ', err);
});
}
}
The error message:
Response {_body: Object, status: 404, ok: false, statusText: "Not Found", headers: Headers…}
_body:Object
headers:Headers
ok:false
status:404
statusText:"Not Found"
type:2
url:null
__proto__:Body
This is probably InMemoryWebApiModule.forRoot related issue. This happens when you load in-memory api, but trying to reach undefined url. The way to solve this is by setting passThruUnknownUrl: true in app.module config:
InMemoryWebApiModule.forRoot(InMemoryDataService, {passThruUnknownUrl: true}) ..
As you can see, it's a 404 error, analyse your request to the server. 404 error means that what you requested wasn't found.
About how you make the request, try ti use .map instead of toPromise.
Try to not make HTTP requests on the constructor, use ngOnInit instead.

Resources