Im using NestJS via HTTPS.
import { NestFactory } from '#nestjs/core';
import { fstat } from 'fs';
import { AppModule } from './app.module';
import {readFileSync} from 'fs'
async function bootstrap() {
const httpsOptions = {
key:readFileSync('tsl/private-key.pem'),
cert:readFileSync('tsl/public-cert.pem')
}
const app = await NestFactory.create(AppModule,{httpsOptions});
await app.listen(3000);
}
bootstrap();
I try to get simple POST request:
#Post()
test(#Body() body){
console.log(body);
}
But output is always {}
POSTMAN:
I readed that nestjs cant parse data correctly. How can i fix that?
Your postman request needs to be set to raw and JSON, not raw and Text
Integrate swagger into your application.
It is an open API and supported by nestjs.
https://docs.nestjs.com/openapi/introduction
Related
I have been getting this error in this small nodejs app while trying to learn using axios on the backend to make request. "unexpected end of file".
axios request file
import axios from "axios";
export const getData = async () => {
let data;
try {
const response = await axios.get(
"https://jsonplaceholder.typicode.com/users"
);
console.log(response);
data = response;
} catch (error) {
console.log(error.message);
return;
}
return data;
};
server.js
import express from "express";
import cors from 'cors';
import axios from "axios";
import { getData } from "./utils/getData.js";
const app = express();
app.use(cors());
app.use(express.json());
app.get("/", async (req, res) => {
let users;
users = await getData();
res.send(users);
})
app.listen(5000, () => {
console.log("server listening at port 5000");
})
You can add below header encoding to your request.
axios.get("url", {
headers: { "Accept-Encoding": "gzip,deflate,compress" }
});
the Brotli decompression bug was fixed in v1.2.2
Bro, go to Package.json--> in dependencies --> check for axios ---> Add 'axios' : '1.1.3'.
This will solve your issue.
I am trying to send a cookie in my response object using NestJS and cookie-parser.
My expected result is that a cookie is attached to my response object and sent to the client (or in this case, postman). My actual result is that I get this error:
web-api_1 | [Nest] 152 - 02/26/2022, 1:15:52 AM ERROR [AccountController] res.cookie is not a function
web-api_1 | TypeError: res.cookie is not a function
web-api_1 | at AccountController.<anonymous> (/app/dist/apps/web-api/webpack:/ourRepo/apps/apis/web-api/src/app/account/account.controller.ts:51:13)
web-api_1 | at Generator.next (<anonymous>)
web-api_1 | at fulfilled (/app/node_modules/tslib/tslib.js:114:62)
web-api_1 | at processTicksAndRejections (node:internal/process/task_queues:96:5)
Here is my code:
// at the top
import { Body, Response, Controller, Patch, Post, Request, UseFilters, UseGuards, Put, Get } from '#nestjs/common';
// later...
#UseGuards(LocalAuthGuard)
#Post('account/sign-in')
async login(#Request() req, #Response() res): Promise<any> {
console.log(43, req.user.email, req.user.id)
const jwt = await this.accountClient.signIn({ email: req.user.email, userId: req.user.id });
const refreshToken = await this.accountClient.generateRefreshToken({email: req.user.email, ipAddress: req.ip})
const cookieOptions = {
httpOnly: true,
expires: new Date(Date.now() + 15*60*1000)
}
res.cookie('refreshToken', refreshToken, cookieOptions);
console.log(45, jwt)
return res.send(jwt);
}
I don't understand what I'm doing wrong. Look at this guy's code and you can see that it works correctly for him; the OP and a helper discuss his issue and they discover his code works correctly. I've copied the form of his code as best as I can. I don't see the issue here.
edit: main.ts to show that I import cookieParser correctly
/**
* This is not a production server yet!
* This is only a minimal backend to get started.
*/
import { Logger } from '#nestjs/common';
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
import { FastifyAdapter, NestFastifyApplication } from '#nestjs/platform-fastify';
import compression from 'fastify-compress';
import multipart from 'fastify-multipart';
import * as cookieParser from 'cookie-parser'; // <----- cookie parser used correctly
import { ClusterService } from '#repo/svc-interfaces';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(AppModule, new FastifyAdapter({
maxParamLength: 400
}));
app.enableCors();
app.use(cookieParser()); // <----- cookie parser used correctly
await app.register(multipart);
await app.register(compression);
const port = process.env.PORT || 3333;
await app.listen(port, '0.0.0.0');
Logger.log(
`🚀 Application is running on: http://localhost:${port}`
);
}
if (environment.production) {
ClusterService.clusterize(bootstrap);
} else {
bootstrap();
}
I figured out what was wrong. I realized there's Express NestJS and Fastify NestJS. I figured the code i was copying from that thread was for Express and so I googled, "fastify nestjs send cookie" and got this page:
https://docs.nestjs.com/techniques/cookies
the solution was to npm install fastify-cookie and follow the docs.
I changed to using the setCookie method they describe in the docs.
Everything's swell.
I decided to rewrite my application from spa vue to nuxt but i faced a problem in spa, in vue i could just import store and used it but in nuxt i cant do the same, i am getting undefined object every time
in vue spa i had folder with some api services and with main api.js which include this code
import axios from 'axios'
import store from '#/store/index'
export default () => {
return axios.create({
baseURL: `http://myip.com/`,
headers: {
Authorization: `Bearer ${store.state.token}`
}
})
}
then in other js files i just import this api.js file and use something like this
import Api from '#/services/Api'
export default {
register (credetinals){
return Api().post('register', credetinals)
},
login (credetinals){
return Api().post('login', credetinals)
}
}
so i had 10 js files services where i include api.js and then in files *.vue i just import this service
how can i do the same in nuxt ?
If you add your state under the /store/index.js it will automatically append in the application, you dont need to import it in your file.
What you can do is try to check the state using:
window.$nuxt.$store.state
Also dont forget to add a condition process.browser since you want to check it in browser.
Here is what I did in my api.js file for your reference:
// Libraries
import axios from 'axios';
// API Instance
export const instance = axios.create({
baseURL: 'http://myip.com/',
headers: {},
validateStatus: status => {
return status;
},
});
// API Interceptors
instance.interceptors.request.use(config => {
if (process.browser) {
const userToken = window.$nuxt.$store.getters.getUserToken;
// Set Authorization token
if (userToken) {
config.headers['Authorization'] = `Bearer ${userToken}`;
}
}
return config;
}, function (error) {
return Promise.reject(error);
});
I have a made a NestJS microservice package and separate NestJS client application for contacting the microservice. Below given is the code used in the client application. In microservice the method used is #messagePattern and it is functional. My question is how a front-end app can contact directly to the microservice without going through the client also how to setup swagger in microservice or test it directly from a postman ?
import { BadRequestException, Injectable, UnauthorizedException } from '#nestjs/common';
import { ClientProxy, ClientProxyFactory, Transport } from '#nestjs/microservices';
import { errorResponse, goodResponse } from 'src/helpers/response.helper';
import { AddContractDTO } from './contract.dto';
#Injectable()
export class ContractService {
private client: ClientProxy;
constructor() {
this.client = ClientProxyFactory.create({
transport: Transport.TCP,
options: {
host: '127.0.0.1',
port: 3011,
},
});
}
public async addContract(data: AddContractDTO) {
const res = await this.client.send<any,any>('contract/addContract', data).toPromise();
console.log(res);
if(!res.success){
throw new BadRequestException(res)
}
return goodResponse(res.data.data,'Contract created');
}
}
You cannot call the service directly. You need to create a controller (to bind to an endpoint) which then can call the service.
Examples can be found in the NestJS Documentation (https://docs.nestjs.com/microservices/basics).
I need to send from my server side to API in request headers "Cookie: token"
In angular universal, for servers Http request methods I use axios. when I try to change headers using Interceptor I have an error "Refused to set unsafe header 'Cookie'" if I send a static cookie like third arguments of axios post all work fine but I have some troubles to dynamically insert token there.
request.servise.ts
import { RequestBody } from './models/request-body.model';
import axios from 'axios';
import {AxiosInstance} from 'axios';
export class Request {
http: AxiosInstance = axios;
constructor() {}
async test(): Promise<any> {
const params = {
param1: 1,
param2: 2,
param3: 3,
}
try {
return this.basicRequest('https://some-request.url', params);
} catch (e) {
console.error('Unknown exception: ', e);
return null;
}
}
private basicRequest(url, params) {
const request = new RequestBody('2.0', 'someMethod', Math.floor(Math.random() * (9999999 - 1000000)) + 1000000, params);
return this.http.post(url, request);
}
}
projects.ts (sever router controller)
import {Router} from 'express';
import {Request} from '../../shared/request.service';
const router: Router = Router();
router.get('/test', async function(req, res, next){
const request = new Request();
try {
const projects = (await request.test()).data.result.records;
res.json(projects);
} catch (e) {
console.error(e);
}
});
export const ProjectsController: Router = router;
By default, angular universal does not transfert cookieswhen using HttpClient. So, you need to do it manually, but you'll get the error you mentionned.
A possible workaround, suggested in that universal github issue, is to bypass xhr2's default security behaviour for unsafe headers
server.ts
import * as xhr2 from 'xhr2';
xhr2.prototype._restrictedHeaders = {};