Sapper $Session change not reflected until page reload - javascript

In my nav.svelte component I have:
{#if $session.token}
${JSON.stringify($session.token)} - ${JSON.stringify($session.token.username)}
{/if}
In login.svelte:
const { session } = stores();
let username, password;
async function onLogin(username, password){
const response = await fetch(`auth/login`, {
method:"POST",
headers:{ 'Content-Type': 'application/json' },
body: JSON.stringify({"username":username,"password":password})
})
if (response.ok) {
const json = await response.json();
session.set({ token: json });
$session.token = json;
goto("/");
} else {
throw new Error(response);
}
}
login.js handler:
req.session.token = user; //parsed.token;
console.log(`req.session.token: ${JSON.stringify(req.session.token)}`);
res.writeHead(200, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify({ token: user }));
server.js:
sapper.middleware({
session: (req, res) => {
console.log(`% req.session.token: ${JSON.stringify(req.session.token)}`);
return ({
token: req.session.token
})}
})
The output in nav.svelte is:
${"token":{"_id":"kjbLgeU8k3GPr6jBd8NkCj","username":"matt123","password":"$2b$10$aXMJc64o9W166OL12CG/A.lWyuB9zdPkaNUsze3Lch6Z2khHaTKY.","access":"user"}} - $undefined
Notice that the data is there, but username outputs undefined. I believe I am doing something wrong but it is obscure.
Added an issue to the tracker on sapper project:
https://github.com/sveltejs/sapper/issues/1711

Related

React / Node - PayPal can't capture a new subscription

I wan't to capture a new paypal subscription from frontend in my backend and give response with the needed data for mongodb.
If I add a body with capture_type: 'OUTSTANDING_BALANCE' (I found that in the manual) I'm getting this error.
So I'm not sure either it's just a wrong body or i totally mess up something else in the backend but so far I can't capture the subscription even so I get a subscription Id from
createSubscription Controller
PayPalScriptProvider
<PayPalScriptProvider options={initialOptions}>
<PayPalSubscriptionButton/>
</PayPalScriptProvider>
PayPal Button
{isPending ? <LoadingMedium /> : null}
<PayPalButtons
createSubscription={(data, actions) => {
return axios
.post(
'/api/subscription',
)
.then((response) => {
return response.data.id;
});
}}
onApprove={(data, actions) => {
axios
.post(`/api/subscription/${data.subscriptionID}/capture`)
.then(() => {
axios
.patch(
`/api/activesubscription`,
{
id: activeSub[0]?._id,
subscriptionID: data.subscriptionID,
}
)
});
});
}}
/>
Route for createSubscription
router.route('/subscription').post(async (req, res) => {
const searchPlan = await SubscriptionAmount.find();
console.log(searchPlan[0]?.subscriptionAmount);
const subscription = await paypalFee.createSubscription(
searchPlan[0]?.subscriptionAmount
);
res.json(subscription);
});
Router for onApprove
router.post('/subscription/:subscriptionID/capture', async (req, res) => {
const { subscriptionID } = req.params;
console.log('subscriptionID', subscriptionID);
const captureData = await paypalFee.captureSubscription(subscriptionID);
console.log('captureData', captureData);
res.json(captureData);
});
createSubscription Controller
async function createSubscription(planId) {
const accessToken = await generateAccessToken();
const url = `${base}/v1/billing/subscriptions`;
const response = await fetch(url, {
method: 'post',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
intent: 'subscription',
plan_id: planId,
}),
});
const data = await response.json();
console.log('data', data);
return data;
}
captureSubscription Controller
async function captureSubscription(subscriptionId) {
const accessToken = await generateAccessToken();
const url = `${base}/v1/billing/subscriptions/${subscriptionId}/capture`;
const response = await fetch(url, {
method: 'post',
body: JSON.stringify({
// capture_type: 'OUTSTANDING_BALANCE',
}),
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
},
});
const data = await response.json();
console.log('data', data);
return data;
}
I'm getting this logs for my data in captureSubscription if I do not pass a body in my captureSubscription Controller:
captureData {
name: 'INVALID_REQUEST',
message: 'Request is not well-formed, syntactically incorrect, or violates schema.',
details: [
{
location: 'body',
issue: 'MISSING_REQUEST_BODY',
description: 'Request body is missing.'
}
]
}
With body I'm getting this error
captureData {
name: 'UNPROCESSABLE_ENTITY',
message: 'The requested action could not be performed, semantically incorrect, or failed business validation.',
details: [
{
issue: 'ZERO_OUTSTANDING_BALANCE',
description: 'Current outstanding balance should be greater than zero.'
}
],
}
ZERO_OUTSTANDING_BALANCE
There is no outstanding balance to capture. An outstanding balance occurs when payments are missed due to failures.
For ordinary (non-outstanding) subscription payments, no captures can be triggered. Subscriptions will capture automatically on the schedule you specify in the plan, that is the point of subscriptions.

Getting Request json data in C# in an HttpPost method

Im in the process of converting my nodejs implementation of my backend to c#. I want to get the request body from my client. How do i access the request body in c#. I then want to use the user input from the client to make another api call using the users parameters.
Here is the front end code
class User {
constructor(userData) {
this.user = userData.id;
this.login = userData.login;
this.password = userData.password;
this.email = userData.email;
this.external_user_id = userData.external_user_id;
this.facebook_id = userData.facebook_id;
this.twitter_id = userData.twitter_id;
this.full_name = userData.full_name;
this.phone = userData.phone;
this.website = userData.website;
this.custom_data = userData.custom_data;
this.user_tags = userData.user_tags;
this.avatar = userData.avatar;
this.created_at = userData.created_at;
this.updated_at = userData.updated_at;
this.last_request_at = userData.last_request_at;
//encrypt the password
}
}
export default User;
async signUp(userCredentials) {
let userForm = new User(userCredentials);
fetch("http://localhost:8080/auth/signup", {
method: 'POST',
body: JSON.stringify(userForm),
headers: {
'Content-Type': 'application/json',
}
})
.then(response => {
if (!response.ok) {
throw Error(`Error message: ${response.statusText}`)
}
console.log(response)
return response.json()
})
.then(json => {
console.log(json);
sessionStorage.setItem('session_token', json.session_token)
this.signIn({ login: userForm.login, password: userForm.password });
})
.catch(error => console.log(error))
}
Here is the nodejs implementation
router.post("/signup", async (req, res) => {
let reqBody = req.body;
console.log(reqBody.password);
console.log(req.headers["cb-token"]);
let cbToken = req.headers["cb-token"];
const userObj = {
user: {
login: req.body.login,
password: req.body.password,
email: req.body.email,
full_name: req.body.full_name,
phone: req.body.phone,
website: req.body.website
}
}
console.log(`token in auth route ${res.locals.session_token}`)
fetch("https://api.connectycube.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
"CB-Token": res.locals.session_token
},
body: JSON.stringify(userObj)
})
.then(response => {
if (!response.ok) {
throw Error(`Error message: ${response.statusText}`)
}
return response.json()
})
.then(data => {
console.log(data)
const resObj = Object.assign(data, { session_token: res.locals.session_token });
res.status(200).json(resObj);
})
.catch(error => {
console.log(error)
res.status(400).json(error)
})
})

Promise rejected in POST login using fetch API in reactjs and Nodejs

I am working on a simple login using POST Fetch in Reactjs with NodeJs API. The code is working good and redirect the page when we login using correct username and password but the problem is when using fake username. I got the error in console.log with Promise : "Rejected". And I still can not figure it why
Here is the code in login.js
async SubmitLogin(event){
event.preventDefault();
//debugger;
console.log(this.state)
await fetch(`http://localhost:4000/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(this.state)
})
.then ((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
// then Read the response as json.
else {
let result = response.json();
console.log(result)
if(result === 'Invalid'){
console.log(response)
alert('Invalid User');
//this.props.history.push('/login');
}
else {
alert('Login Sucessfull');
this.props.history.push('/home');
}
}
})
.catch((err) => {
console.error();
})
}
in my server.js, I used express-session like this:
//sales login
app.post('/login', jsonParser, (req, res) => { //jsonParser,
let username = req.body.username;
let password = req.body.password;
console.log("req: ",req.body);
if (username && password) {
dbConn.query(`SELECT * FROM user_tbl WHERE username = ? AND password = ?`, [username, password], (err, results, fields) => {
if (results.length > 0) {
req.session.loggedin = true;
req.session.username = username;
res.redirect('/home');
console.log(results)
console.log("req: ", req.body);
} else {
res.send('Incorrect Username and/or Password!');
}
res.end();
});
} else {
res.send('Please enter Username and Password!');
res.end();
}
});
app.get('/home', (req, res) => {
if (req.session.loggedin) {
res.send('Welcome back, ' + req.session.username + '!');
} else {
res.send('Please login to view this page!');
}
res.end();
});
and this is the result I got in console:
hopefully my question is clear.
I think your response doesnt come json format.You cant parse string to json.
Your response should be like this res.send({success:false , message : "Incorrect Username and/or Password!"})
After many suggestions and anwers, finally I can figure out how to solved this problem. Here is the code in login.js
//submit function
async SubmitLogin(event){
event.preventDefault();
console.log(this.state)
await fetch(`http://localhost:4000/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify(this.state)
})
.then ((response) => {
if(response.status === 401) {
throw new Error('Unauthorized');
}
//return response.json();
})
.then((result) => {
console.log(result);
this.props.history.push('/home');
alert('Login Sucessfull');
})
.catch((err) => {
console.log();
})
}
and in the backend, I didn't change anything.

Fetch API response with react and Express.js won't show any result with console.log

I have a login form that sends data to an Express.js backend using fetch. On the client side, when I want to display the results of the fetch call when it completes nothing is displayed (and it never reaches the data callback). I don't seem to be getting any errors, but I know that the data is successfully being sent to the backend.
Here's the Express.js server code:
const express = require('express');
const User = express.Router();
const bcrypt = require('bcrypt');
const user = require('../Models/user');
this is edited
function loginRouteHandler(req, res) {
user.findOne(
{
where: {
userName: req.body.userName,
},
},
)
.then((data) => {
if (bcrypt.compareSync(req.body.password, data.password)) {
req.session.userName = req.body.userName;
req.session.password = req.body.password;
console.log(req.session);
res.status(200).send('Success!');
} else {
res.status(400).send('some text');
}
});
}
User.route('/').get(getRouteHandler);
User.route('/register').post(postRouteHandler);
User.route('/login').post(loginRouteHandler);
module.exports = User;
And here's the fetch call:
fetch('http://localhost:4000/login',{
method: 'POST',
headers: {
'Accept': 'application/json,text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify({
userName: this.state.userName,
password: this.state.password,
}),
}).then((response)=>{
if(response.ok){
console.log(response)
}
else {
console.log("a problem")
}
}).then((data)=>{
console.log(data)
});
In your loginRouteHandler, if the bcrypt compare succeeds nothing is returned in the response. So in the first branch of the if statement, put res.send('Success!') or something similar.
Here's an example:
function loginRouteHandler(req, res) {
user.findOne(
{
where: {
userName: req.body.userName,
},
},
)
.then((data) => {
if (bcrypt.compareSync(req.body.password, data.password)) {
req.session.userName = req.body.userName;
req.session.password = req.body.password;
console.log(req.session);
res.status(200).send('Success!');
} else {
res.status(400).send('some text');
}
});
}
UPDATE: you're also not getting the output of the fetch response with .text() or .json(). You have to update the fetch call to the following:
fetch(/* stuff */).then((response)=>{
if(response.ok){
console.log(response)
}
else {
console.log("a problem")
}
return response.text()
}).then((data)=>{
console.log(data)
});
Remove ok from response.ok
Remove .then((data)=>{ console.log(data) });
And check console log.
}).then((response)=>{
if(response){
console.log(response)
}
else {
console.log("a problem")
}
}).then((data)=>{
console.log(data)
});

How use await keyword along with asyncstorage setitem for server response?

I'm trying to use asyncstorage in my react native app.The problem is the server response I'm getting takes some delay so I want to wait for the response then I want to use that responseData.user_id to be saved in my app.I'm using nodejs as backend and mysql db.So after user registration I'm inserting it to db at the same time I've written another query for fetching their user_id (PK).So this responseData is getting to client and I'm trying to take that user_id from the response.So I've written something like this
onPressRegister = async () => {
try {
let response = await fetch('http://192.168.1.2:3000/users/registration', {
method: 'POST',
headers: {
'Accept': 'applictaion/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
contact: this.state.contact,
password: this.state.password,
})
});
let responseData = await response.json();
if (responseData) {
try {
Action.firstScreen();
await AsyncStorage.setItem('userid', JSON.stringify(responseData.userData.phone_no));
}
catch (e) {
console.log('caught error', e);
}
}
} catch (error) {
console.error(error)
}
}
And in my next screen I'm accessing the userid like this.And passing it the next API call like this.
getUserId = async () => {
let userId = await AsyncStorage.getItem('userid');
return userId;
}
onPressYes = (workType) => {
this.getUserId().then((userId) => {
this.setState({userId:userId})
})
fetch('http://192.168.1.2:3000/users/user_request',{
method:'POST',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
workType,
phone:this.state.userId
})
})
.then(response => response.json())
.then((responseData) => {
this.setState({
data:responseData
});
});
}
But this is the error I'm getting.
Try this:
onPressRegister = async () => {
try {
let response = await fetch('http://192.168.1.6:3000/users/registration', {
method: 'POST',
headers: {
'Accept': 'applictaion/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
contact: this.state.contact,
password: this.state.password,
})
});
let responseData = await response.json();
if (responseData) {
try {
await AsyncStorage.setItem('userid', JSON.stringify(responseData.user_id));
}
catch (e) {
console.log('caught error', e);
}
}
} catch (error) {
console.error(error)
}
}
To access the value in some other component:
getUserId = async () => {
let userId = await AsyncStorage.getItem('userid');
return userId;
}
componentWillMount() {
this.getUserId().then((userId) => {
console.log(userId);
})
}

Categories

Resources