Here's the javascript code that request POST data to my server. when I print out the body data, It seems works fine, but Koa doesn't even parse 'body' from the request(using koa-bodyparser). I have no idea why this happens, It literally worked like a week ago.
Browser
jQuery(document).ready(function($) {
$(".mypage_container .btn-block").click(async() => {
let payload = {
email: $('#username').val(),
password: $('#password').val(),
country: $('#CountriesDropDownList').val(),
firstname: $('#firstname').val(),
lastname: $('#lastname').val(),
gender: checkGender(),
address1: $('#address1').val(),
zipcode: $('#zipcode').val(),
mobile: $('#mobile').val(),
newsletter: newsLetter()
}
let option = {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
}
try {
let res = await fetch('/signup', option)
} catch (e) {
console.error("failed to send signup request", e)
}
})
})
Server
router.post('/signup', async (ctx, next) => {
let data = ctx.request.body
console.log(ctx.request.body, ctx.request) // says undefined on first variable, request info without 'body' from the request.
try {
let user = new User(data)
await user.save()
ctx.body = data
} catch (e) {
console.error(e)
}
})
You need to use co-body to parse the posted data:
const parse = require('co-body');
router.post('/signup', async (ctx, next) => {
let data = await parse(ctx);
console.log(data);
try {
let user = new User(data)
await user.save()
ctx.body = data
} catch (e) {
console.error(e)
}
})
This should work ...
Related
React Native
this my code. when i request for data push in database then react native App.js fetch function is not execute you can see my code and solve this bug...
this is my react native screen code where i function is not calling backend
App.js
const postdata = async () => {
const data = {cname, cphone, ccity, caddress, cemail, gender}
// 63064232cf92b07e37090e0a
const res = await fetch(`http://192.168.43.220:8000/Newcustomer/${id}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
cname, cphone, ccity, caddress, cemail, gender
})
})
const data2 = await res.json();
console.log(data2);
if (!data2) {
window.alert('error in get data2');
}
else {
setdata(data2);
window.alert("Costomer Added")
navigation.navigate("Home")
}
}
Back End
Node js
this is my node js code. it code is properly working when i try to postman
app.js
app.patch('/Newcustomer/:id', async (req, res) => {
const _id = req.params.id;
getschema.findByIdAndUpdate(_id, {
$push: {
costomer:
{
cname: req.body.cname,
cphone: req.body.cphone,
ccity: req.body.ccity,
caddress: req.body.caddress,
cemail: req.body.cemail,
gender: req.body.gender
},
}
})
.then(data => {
res.status(201).json(data);
}).catch(err => {
console.log(err);
})
})
This is the error that I get:
"You have created a new client application that use…i/web/guides/gis-migration) for more information."
here are my codes on server, the statement inside console.log doesnt even show:
static async googleLogin(req, res, next) {
try {
console.log("masuk google login server")
const { id_token } = req.body
const client = new OAuth2Client(process.env.GOOGLE_CLIENT_ID)
const ticket = await client.verifyIdToken({
idToken: id_token,
audience: process.env.GOOGLE_CLIENT_ID
});
const payload = ticket.getPayload()
const email = payload.email
let password = email.toString().split('#')
password = password[0]
let user = await User.findOne({ where: { email } })
if (!user) {
let newUser = { email, password }
let createUser = await User.create(newUser)
const payload = {
id: createUser.id,
email: createUser.email
}
const access_token = generateToken(payload)
return res.status(201).json({ access_token })
} else {
const payload = {
id: user.id,
email: user.email
}
const access_token = generateToken(payload)
return res.status(200).json({ access_token })
}
} catch (err) {
console.log(err)
return next(err)
}
}
the console.log in my client also doesnt show
function onSignIn(googleUser) {
console.log("masuk client oauth")
$.ajax({
method: "POST",
url: `${baseUrl}/users/google-login`,
data: {
id_token: googleUser.getAuthResponse().id_token
}
})
.done((response) => {
console.log(response, "client response")
localStorage.setItem("access_token", response.access_token)
checkLocalStorage();
})
.fail((err) => {
console.log(err, "error client");
})
.always(() => {
authentication()
})
}
i tried deleting cache and run my app again, recreate a new project on google api (which genereated new ID). they didnt work
when I post this method in my MongoDB database it's working properly, but when I wanted to get it it's showing {"message": "Unauthorized Access"} in my http://localhost:5000/my site. The thing which I wanted everything is ok. But get is not working
//server side code
app.post("/my", async (req, res) => {
const my = req.body;
const result = await myCollection.insertOne(my);
res.send(result);
});
app.get("/my", async (req, res) => {
const query = {};
const cursor = myCollection.find(query);
const services = await cursor.toArray();
res.send(services);
});
//client side code
const onSubmit = (data, event) => {
const url = `http://localhost:5000/service`;
fetch(url, {
method: "POST",
headers: {
"content-type": "application/json",
},
body: JSON.stringify(data),
})
.then((res) => res.json())
.then((result) => {
setIsReload(!isReload);
if (result) {
alert("Add Successful");
}
});
const order = {
email: user.email,
name: event.target.name.value,
description: event.target.description.value,
price: event.target.price.value,
quantity: event.target.quantity.value,
};
axios.post(`http://localhost:5000/my`, order).then((res) => {
const { data } = res;
console.log(data);
if (data.insertedId) {
alert("Inserted");
}
event.target.reset();
console.log(res);
});
};
I'm trying to sign up new user, when I'm sending the post request the server register the user well, and I can see them in my data base, but I can't see the success log in my console (I can catch the error and it logs in my console).
Server side code:
var express = require("express");
const { Error } = require("mongoose");
const passport = require("passport");
var router = express.Router();
const User = require("../models/user");
const catchAsync = require("../utils/catchAsync");
router.post(
"/register",
catchAsync(async (req, res) => {
try {
const { email, username, password } = req.body;
const user = new User({ email, username });
await User.register(user, password);
} catch (e) {
throw new Error("Error signing up");
}
})
);
module.exports = router;
Client side code:
const sumbitHandler = async (data) => {
const { username, email, password } = data;
try {
await fetch("http://localhost:9000/users/register", {
method: "POST",
body: JSON.stringify({
username,
email,
password,
}),
headers: {
"Content-Type": "application/json",
},
})
.then((res) => {
if (res && !res.ok) {
throw new Error("ERROR");
}
console.log("Success");
})
.catch((e) => {
console.log(e.message);
});
} catch (e) {
console.log(e.message);
}
};
You are mixing the async/await style and the older .then() Promise-style. Choose one or the other (I strongly recommend async/await)
You are not transforming fetch's response into JSON, leaving it in Promise state.
Your server is never responding to the client! You need to add res.end(), res.send(), res.json() or something.
const sumbitHandler = async (data) => {
const { username, email, password } = data;
try {
const response = await fetch("http://localhost:9000/users/register", {...});
const serverResponse = await response.text(); // or response.json() if your servers sends JSON back
console.log("Success! serverResponse is = ", serverResponse ); // "Done!"
} catch (e) {
console.log(e.message);
}
};
Server :
...
await User.register(user, password);
res.send("Done!"); // or res.json({ status : "ok" }); etc.
I'm doing requests to my API server to authenticate a user, that's not the problem. The problem is that I don't know why my async function doesn't return anything, and I get an error because the data that I want from this function is undefined.
Don't worry if the error management is ugly and in general I can do this better, I'll do that after fixing this problem.
Utils.js class
async Auth(username, password) {
const body = {
username: username,
password: password
};
let req_uuid = '';
await this.setupUUID()
.then((uuid) => {
req_uuid = uuid;
})
.catch((e) => {
console.error(e);
});
let jwtData = {
"req_uuid": req_uuid,
"origin": "launcher",
"scope": "ec_auth"
};
console.log(req_uuid);
let jwtToken = jwt.sign(jwtData, 'lulz');
await fetch('http://api.myapi.cc/authenticate', {
method: 'POST',
headers: { "Content-Type": "application/json", "identify": jwtToken },
body: JSON.stringify(body),
})
.then((res) => {
// console.log(res);
// If the status is OK (200) get the json data of the response containing the token and return it
if (res.status == 200) {
res.json()
.then((data) => {
return Promise.resolve(data);
});
// If the response status is 401 return an error containing the error code and message
} else if (res.status == 401) {
res.json()
.then((data) => {
console.log(data.message);
});
throw ({ code: 401, msg: 'Wrong username or password' });
// If the response status is 400 (Bad Request) display unknown error message (this sould never happen)
} else if (res.status == 400) {
throw ({ code: 400, msg: 'Unknown error, contact support for help. \nError code: 400' });
}
})
// If there's an error with the fetch request itself then display a dialog box with the error message
.catch((error) => {
// If it's a "normal" error, so it has a code, don't put inside a new error object
if(error.code) {
return Promise.reject(error);
} else {
return Promise.reject({ code: 'critical', msg: error });
}
});
}
Main.js file
utils.Auth('user123', 'admin')
.then((res) => {
console.log(res); // undefined
});
Your Async function must return the last promise:
return fetch('http://api.myapi.cc/authenticate', ...);
or await the result and return it:
var x = await fetch('http://api.myapi.cc/authenticate', ...);
// do something with x and...
return x;
Notice that you don’t need to mix promise syntax (.then) with await. You can, but you don’t need to, and probably shouldn’t.
These two functions do exactly the same thing:
function a() {
return functionReturningPromise().then(function (result) {
return result + 1;
});
}
async function b() {
return (await functionReturningPromise()) + 1;
}
await is not to be used with then.
let data = await this.setupUUID();
or
let data=null;
setupUUID().then(res=> data = res)
I would try something like this:
const postReq = async (jwtToken) => {
const body = {
username: username,
password: password,
};
try {
const res = await fetch('http://api.myapi.cc/authenticate', {
method: 'POST',
headers: { "Content-Type": "application/json", "identify": jwtToken },
body: JSON.stringify(body),
})
if (res) {
if (res.status == 200) {
return res.json();
} else if (res.status == 401) {
const data = res.json();
console.log(data.message)
throw ({ code: 401, msg: 'Wrong username or password' });
} else if (res.status == 400) {
throw ({ code: 400, msg: 'Unknown error, contact support for help. \nError code: 400' });
}
}
} catch (err) {
console.error(err)
}
};
const Auth = async (username, password) => {
const jwtData = {
"origin": "launcher",
"scope": "ec_auth"
};
try {
const req_uuid = await this.setupUUID();
if (req_uuid) {
jwtData["req_uuid"] = req_uuid;
const jwtToken = jwt.sign(jwtData, 'lulz');
return await postReq(jwtToken);
}
} catch (err) {
console.error(err);
};
}