How to solve nestjs fastify error TypeError: response.status(...).json is not a function - nestjs-fastify

TypeError: response.status(...).json is not a function
at HttpExceptionFilter.catch (/home/muhammedali/Documents/100haryt_v2/src/common/http/http-exception.filter.ts:23:29)
at ExceptionsHandler.invokeCustomFilters (/home/muhammedali/Documents/100haryt_v2/node_modules/#nestjs/core/exceptions/exceptions-handler.js:33:26)
at ExceptionsHandler.next (/home/muhammedali/Documents/100haryt_v2/node_modules/#nestjs/core/exceptions/exceptions-handler.js:13:18)

response
.status(status)
.json({
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
});
instead of using the above code. try to change like as below
response
.status(status)
.send({
statusCode: status,
timestamp: new Date().toISOString(),
path: request.url,
});

Related

Pass variable from client to server-side in NEXTJS

I have already done this but Idk why when I try to apply it again in another code it does not work. So I have this code "Client side"
const response = await fetch("/api/ipfs", {method: "POST", DATA: "holaaaa"});
if (!response.ok) {
throw new Error(`Error: ${response.status}`);
}
const result = await response.json()
console.log(result.result)
And this one that is the "Server side"
function uploadIPFS(req, res) {
axios.get(req.body).then(r => {
let metadata = r.data
res.status(200).json({ metadata: metadata });
}).catch(err => console.error(err))
}
export default function handler(req, res) {
if (req.method==='POST') {
uploadIPFS(req, res);
}
}
This is working with another api file I have, so I implement another file that is this one and in another function of the client side make a call to the new api file, the problem is that the variable I want to pass from client to server is the body one, the one that says "holaaaa", is it not working and it throws this error.
API resolved without sending a response for /api/ipfs, this may result in stalled requests.
Error: Cannot read properties of null (reading 'replace')
at dispatchHttpRequest (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\axios\lib\adapters\http.js:161:23)
at new Promise (<anonymous>)
at httpAdapter (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\axios\lib\adapters\http.js:49:10)
at dispatchRequest (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\axios\lib\core\dispatchRequest.js:58:10)
at Axios.request (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\axios\lib\core\Axios.js:109:15)
at Axios.<computed> [as get] (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\axios\lib\core\Axios.js:131:17)
at Function.wrap [as get] (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\axios\lib\helpers\bind.js:9:15)
at uploadIPFS (webpack-internal:///(api)/./pages/api/ipfs.js:17:11)
at handler (webpack-internal:///(api)/./pages/api/ipfs.js:37:9)
at Object.apiResolver (C:\Users\berna\Desktop\Programming\Web development\BlueToken\bluetoken\node_modules\next\dist\server\api-utils\node.js:184:15) {
config: {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
adapter: [Function: httpAdapter],
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: { FormData: [Function] },
validateStatus: [Function: validateStatus],
headers: {
Accept: 'application/json, text/plain, */*',
'User-Agent': 'axios/0.27.2'
},
method: 'get',
url: '',
data: undefined
},
url: '',
exists: true
}
any idea abt this?
The request to your API is made, but you are not adding anything to the request body. I think you need to change your DATA property in your fetch call to body:
const response = await fetch("/api/ipfs", { method: "POST", body: "holaaaa" });
Also, since you are passing that body parameter to the axios.get() method in your API handler, I assume it's supposed to be a URL?

ClientFunction: _axios2 is not defined

I'm running TestCafe for UI automation, using ClientFunctions to trigger API requests (so that I can pass along session cookies).
Currently I have a ClientFunction with fetch which works fine... except we're now testing IE 11 and Fetch is unsupported.
Fetch code:
const fetchRequestClientFunction = ClientFunction((details, endpoint, auth, method) => {
return window
.fetch(endpoint, {
method,
credentials: 'include',
headers: new Headers({
accept: 'application/json',
'Content-Type': 'application/json',
}),
body: JSON.stringify(details),
})
.then(httpResponse => {
if (httpResponse.ok) {
return httpResponse.json();
}
return {
err: true,
errorMessage: `There was an error trying to send the data ${JSON.stringify(
details
)} to the API endpoint ${endpoint}. Status: ${httpResponse.status}; Status text: ${httpResponse.statusText}`,
};
});
});
However when I try to switch it to axios... not so much:
import axios from 'axios';
const axiosRequest = ClientFunction((details, endpoint, auth, method) => {
return axios({
method,
auth,
url: endpoint,
data: details,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
timeout: 3000,
})
.then(httpResponse => {
if (httpResponse.status < 300) return httpResponse;
return {
err: true,
errorMessage: `There was an error trying to send the data ${JSON.stringify(
details
)} to the API endpoint ${endpoint}. Status: ${httpResponse.status}; Status text: ${httpResponse.statusText}`,
};
});
});
Tried using window.axios, and also passing axios as a dependency. I've also tried making the axios request without the ClientFunction... and despite getting response of 200, the website wasn't updated as expected.
Each time I either get _axios2 is not defined or window.axios is not a function. I would greatly appreciate some guidance here.
TestCafe ClientFunctions allow only serializable objects as dependencies. You need to have axios on the client side to send such a request.

Vue.js+Firebase: 401 error, 'unauthorized'

When I try to use post method in my Vue project:
this.$http.post("https://vuejs-blog-b91df.firebaseio.com/posts.json", this.blog).then(function(data) {
console.log(data);
this.submitted = true;}
the console throws me an error:
Failed to load resource: the server responded with a status of 401 (Unauthorized)
Uncaught (in promise)
Response
body: {error: "Permission denied"}
bodyText: "{↵ "error" : "Permission denied"↵}↵"
headers: Headers {map: {…}}
ok: false
status: 401
statusText: "Unauthorized"
url: "https://project-name.firebaseio.com/posts.json"
data: (...)
__proto__: Object
Where and how should I put firebase project apiKey and other authorization data to succeed?
Authentication with access_token
Based on firbase authentication documentation, I think you must change your request URL to smth like this:
const token = 'token'; // get token somewhere
this.$http
.post(`https://vuejs-blog-b91df.firebaseio.com/posts.json?access_token=${token}`, this.blog)
.then((data) => {
console.log(data);
this.submitted = true;
});
Authentication with ID token
Or you may use ID token authentication like this:
const token = 'token'; // get token somewhere
this.$http
.post(`https://vuejs-blog-b91df.firebaseio.com/posts.json?auth=${token}`, this.blog)
.then((data) => {
console.log(data);
this.submitted = true;
});
Here you can find how to get ID token on client

What could cause a promise to fail in Nativescript angular2?

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.

Meteor HTTP.post not working with Trello API

I'm trying to create a webhook through the Trello API by using Meteor's HTTP.post method like this:
HTTP.post('https://api.trello.com/1/webhooks?key=...&token=...', {
params: {
idModel: '...',
callbackURL: '...'
},
}, function(error, result) {...});
The request works but the response i get is "Invalid value for idModel". However, if i try the same request using jQuery:
$.ajax({
type: 'POST',
url: https://api.trello.com/1/webhooks?key=...&token=...,
data: {
idModel: '...',
callbackURL: '...'
},
});
Everything works fine (i.e. the webhook is created and data is returned). Somehow Meteor's method seems to make it impossible for Trello to parse the idModel field. Any ideas what might be behind this? Am i doing something wrong or is there a bug?
I solved it by setting the Content-Type header to application/x-www-form-urlencoded. It was sent as text/plain before.
HTTP.post('https://api.trello.com/1/webhooks?key=...&token=...', {
params: {
idModel: '...',
callbackURL: '...'
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}, function(error, result) {...});
Try using data instead of params:
HTTP.post('https://api.trello.com/1/webhooks?key=...&token=...', {
data: {
idModel: '...',
callbackURL: '...'
},
}, function(error, result) {...});
Supplementing this page because I had the same problem doing this in golang. I solve it by adding
req.Header.Add("Content-Type", "application/json")
It is confusing that the 400 message is about an invalid idModel.

Resources