Posting Formdata on nestjs server - nestjs

I am trying to make a post request on my nestjs server in a formdata format. I have tried out:
#Post()
createUser(
#Body(new ValidationPipe({transform: true})) createUserDTO:CreateUserDTO,
) {
console.log("creating new user", createUserDTO)
}
but so far what i console.log comes out to:
creating new user {}
or an empty DTO. Can you kind people on the internet advise me on how to fix my issue? Thanks

Related

Getting an empty object in Axios Get Request

I am trying to set up a get route using axios. I am using React. I am trying to get the state of user.
user.user logs:
{_id: '62c5bdda933b818e12bef350', username: 'JordanF', Profiles: Array(9), createdAt: '2022-07-06T16:52:42.396Z', updatedAt: '2022-07-09T19:24:10.523Z', …}
I am trying to display username on my page. But at the moment I can't even log the username to my backend, so won't be able to search my db.
Profile.jsx
function getUser(data) {
console.log(data)
axios({
url: `http://localhost:3000/profiles`,
method: "GET",
data: data
})
.then((response) => console.log(response))
}
useEffect(() => {
setProfileList(profiles)
getUser(user.user)
},[]);
Data logs the data in the front end that I would like to get in the backend
BackEnd Controller
I have tried a lot of different syntax for this, this is my most recent. In the backend temrinal my console.log hits, and req.body returns an empty object.
async function getUser(req,res){
console.log('getUser hit')
function log(){
console.log(req.body)
return req.body
}
await log()
}
Yup! I was being silly. GET requests are only really concerned with params. I changed my route, so that the User's ID was in the URL path, and used req.params.id and everything worked out!

how can i check in the data is passing to server from angular to node.js

Got the http-service -
public addProductsToBag(
productId: string,
): Observable<IAddProductsToBagResponse> {
const baseUrl = ENDPOINT;
return this.http.post<IAddProductsToBagResponse>(baseUrl, {
productId,
});
}
Got the productId (console.logged it).
Sure the endpoints are the same.
The router -
router.post(
"/",
auth,
addProductsToBag,
);
I do not get anything fron the controller.
The server controller request -
interface IAddProductsToBagRequest extends IAuthenticatedRequest {
readonly body: Readonly<{
productId: string[];
}>;
}
What is the problem?
Well, In order to receive json data, you need to enable express's json middleware on the server.
In server.js file do following.
app.use(express.json());
Then you should get the json data.
Edit: First check if your request is getting sent from the frontend.
After checking code, in order to send request you will need to subscribe to that method, then only request will be sent.

problem on creating new document in mongoose

i want to add a new document with mongoose
but it just creates only the _id without all the details I entered
in the postman i entered:
{
"name":"jhon",
"email":"jhon11#gmail",
"password":"1234"
}
but got this in the res:
{
"_id": "6072e8d3f0f69037cc05b8cb",
"__v": 0
}
my code:
const addUser = async (req, res) => {
try {
let user = new User(req.body)
await user.save()
res.send(user)
}
catch (error) {
res.status(400).send(`error ${error}`)
}
}
and the schema is:
const userSchema=mongoose.Schema({
name:{
Type:String
},
email:{
Type:String
},
password:{
Type:String,
}
})
thanks for any advice.
Postman isn't very straight forward in explaining how it sends out post requests. I'm saying this because I also had some run-downs with it. It is most likely sending out an empty body in the request. Open up postman again, and go to the post request you created. We already know your request reached the backend server, so it means the url is fine, and that its type is in fact a post request. So now, click on the Body tab.
I'm gonna go ahead and guess you chose the raw option amongst the million available options there, correct?
In the textarea zone, insert your raw json again, as you did before:
{
"name":"jhon",
"email":"jhon11#gmail",
"password":"1234"
}
But wait! before sending that out, look to the right. There's a combo-box there. A dropdown. A select menu (whatever you wanna call it).
By default, postman chooses TEXT as the default option. Change it to JSON!
NOW IT'S GONNA WORK!
Also, maybe before sending that out for test spin, i'd recommend putting a console.log in bewtween your lines and see what prints out, like so:
const addUser = async (req, res) => {
try {
let user = new User(req.body)
console.log('req.body is:', req.body)
await user.save()
res.send(user)
}
catch (error) {
res.status(400).send(`error ${error}`)
}
If your req.body is still being presented as empty, then my next question to you would be: Are you using bodyParser on your server? Because could also be the case. Body parser, as its name suggests, is meant for dealing with req.body, so it could actually be readable. try adding a body parser to your express server.
Good luck!
I hope that helps.

React + Nodejs : Share code between Front and Back End

I have a front-end built in React and Backend built in Nodejs (framework Adonisjs). I want to share some code between The Client and the Server. My Team can't use NPM or GitHub to do it, because of Company Policies.
Reading NPM docs, I found a possible solution:
On package.json I included the following line in "dependencies" entry:
"sharedCodeModule": "index.js:../<sharedCodeFolder>"
Doing that, I could import the module in both Front and Backend. The thing is that I've never seen such solution for this problem (not that I searched a lot). Anyone can see any problems in this approach?
Ps: Sorry for bad English. Not a native speaker.
Not sure I understand the question, yet, if your backend is perfectly set to make post and get requests, your front end should only take call your backend funcionalities.
Try to use npm axios , and you can have a example.js file like:
import axios from 'axios';
export default axios.create({
baseURL: 'http://127.0.0.1:8000/'
})
where you switch that baseURL for what you actually need. And then on your frontend you should have axios post and get requests, for example, you either import the above file in the file of the frontend component and do the post/get like:
import axiosFunc from "./example";
class WhateverComp extends Component {
constructor(props) {
super(props);
this.state = {
(...)
};
}
(...)
handleSubmit = async () => {
const response = await axiosFunc.post("/yourEndPointHere", {
exampleParam: this.state.param
});
message.success("success.");
};
(...)
Or, as you can see in the link I gave you, with axios, you make call it directly and do your requests like the example below:
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Again, I'm not sure I understood what you actually want to do, I hope axios helps you.

Setting a test header in GraphQL Playground that I want to use causes "Server cannot be reached"

So I've created a bunch of mutations and queries and stitched them together that works and wanted to introduce authentication into the mix. I added an HTTP Header "x-token" to hold my sign-in token to be able to delete things like their job or the user itself.
const getMe = async req => {
const token = req.headers['x-token'];
if (token) {
try {
return await jwt.verify(token, "notSoSecret");
} catch (e) {
throw new AuthenticationError(
'Your session expired. Sign in again.',
);
}
}
};
const server = new ApolloServer({
typeDefs: schema,
resolvers,
formatError: error => {
// remove the internal sequelize error message
// leave only the important validation error
const message = error.message
.replace('SequelizeValidationError: ', '')
.replace('Validation error: ', '');
return {
...error,
message,
};
},
context: async ({ req }) => {
const me = await getMe(req);
return {
models,
me,
secret: "notSoSecret",
}
},
path: "/graphql"
});
server.applyMiddleware({ app });
sequelize.sync().then(async () => {
createUsersWithJob();
});
app.get("/playground", graphiql({ endpoint: "/graphql" }));
const handler = serverless(app);
export { handler };
const createUsersWithJob = ... //creates seed data
So when I add the token and I look into my command line console, I actually see that I'm setting the header that I want, but it loops over and over again and doesn't stop. Also playground gets an error "Server cannot be reached"
{
"error": "Response not successful: Received status code 400"
}
and running a deleteUser mutation does not work, or any other mutation and query for that matter until I remove the HTTP Header that I set on playground.
There is a secondary issue where everything in this root file runs twice, but that's not as big for me at the moment as the header issue outlined.
If anyone has any insight into this, I'd love to know more. Thanks in advance.
edit: just a quick edit to say that it works fine when I hardcode a pre-existing user.
I had quite a struggle to get the React version of GraphQL Playground working within a very simple html setup, but I figured something out that might help you as well (fingers crossed).
I added a headers section to the config in the GraphQLPlayground.init call, like so:
const root = document.getElementById('root');
GraphQLPlayground.init(root, {
endpoint: "/graphql",
headers: {
"Authorization": "Bearer " + token
}
})
I have an element with an id root since this is embedded in HTML.
Not sure this will help you though, as I just noticed from your code sample you're calling graphiql which is a different GraphQL client than GraphQL Playground..
GraphIQL: https://github.com/skevy/graphiql-app
GraphQL Playground: https://github.com/prisma/graphql-playground

Resources