Problem is that in my second post request I cannot get req.body. Neither console.log nor req.body show something.
In the first post request, everything seems to work just fine. And it was also working before I start to re-arrange code. I even change the type of the reply to send, but receiving the old message (status ok).
I do not understand what's going on. Any help, please?
Glitch: https://uatyroni-exercise-tracker.glitch.me - live app
code: https://glitch.com/~uatyroni-exercise-tracker
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const shortid = require('shortid');
const cors = require("cors");
//Setting MongoDB
const mongoose = require("mongoose");
mongoose.connect(process.env.MONGO_URI);
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static("public"));
app.get("/", (req, res) => {
res.sendFile(__dirname + "/views/index.html");
});
//Defining Schema & Model
let Schema = mongoose.Schema;
let userSchema = new Schema({
id: { type: String, unique: true, default: shortid.generate },
user: String,
exercise: [{
description: String,
duration: Number,
date: {}
}]
});
let userModel = mongoose.model("Users", userSchema);
let exerciseSchema = new Schema({
userId: String,
description: String,
duration: Number,
date: String
});
let exerciseModel = mongoose.model("Exercies", exerciseSchema);
//THE POST PROCESS
app.post("/api/exercise/new-user", (req, res) => {
let userName = req.body.username;
let userNew = new userModel({ user: userName });
userModel
.find()
.exec()
.then(data => {
data = data.filter(obj => obj["user"] === userName);
console.log("I am the data: " + data);
if (data.length === 0) {
userNew
.save()
.then(result => {
res.json(result);
})
.catch(err => {
console.log(err);
res.json({ error: err });
});
} else {
res.json({ Error: "User is already registered in the database" });
}
});
});
app.post("/api/exercise/add", (req, res) => {
console.log('reqbody is: ' + req.body.description)
let newDate = '';
if (req.body.date == '') {
newDate = new Date().getFullYear() + '-' + new Date().getMonth() + '-' + new Date().getDate();
}
let newExercise = {
description: req.body.description,
duration: req.body.duration,
date: newDate
}
userModel.findById(req.body.userid, (err, data) => {
if (data.length == null)
res.json({
error: "User is not registered. Please register a user first."
});
else {
res.json(data)
}
});
});
// Not found middleware
app.use((req, res, next) => {
return next({ status: 404, message: "not found" });
});
// Error Handling middleware
app.use((err, req, res, next) => {
let errCode, errMessage;
if (err.errors) {
// mongoose validation error
errCode = 400; // bad request
const keys = Object.keys(err.errors);
// report the first validation error
errMessage = err.errors[keys[0]].message;
} else {
// generic or custom error
errCode = err.status || 500;
errMessage = err.message || "Internal Server Error";
}
res
.status(errCode)
.type("txt")
.send(errMessage);
});
const listener = app.listen(process.env.PORT || 4000, () => {
console.log("Your app is listening on port " + listener.address().port);
});
Related
This is my index.js. When I hit my API using postman, there is a bug in my getdata() method code that causes it to return the else statement rather than finding the requested resource. I'm not sure why the data targeting by ID can't be found. When I use console.log to test my code, the try statement is entered but did not find anything from the database and catch statement is returned.
const connectToMongo = require('./db');
var cors = require('cors');
const express = require('express');
const bodyParser = require('body-parser');
const photo = require('./models/photoModel');
const formidable = require('formidable');
const fs = require('fs');
const photoModel = require('./models/photoModel');
connectToMongo();
const app = express();
app.use(cors());
const port = 5000;
//app.use(express.json());
app.use(bodyParser.json());
const userData = (req, res) => {
const form = new formidable.IncomingForm();
console.log('1');
form.parse(req, (err, fields, file) => {
console.log('2');
if (fields) {
console.log('3');
const { email, mno, name } = fields;
if (!email || !mno || !name) {
console.log('4');
return res.status(400).json({
error: 'Fill all the fields',
});
}
}
if (file.photo) {
if (file.photo.size > 4000000) {
return res.status(400).json({
error: 'image size is too long',
});
}
const user = new photo(fields);
user.photo.data = fs.readFileSync(file.photo.filepath);
user.photo.contentType = file.photo.type;
user.save((err, user) => {
if (err) {
return res.status(400).json({
error: 'Not save in db',
});
}
console.log('above json');
res.json(user);
});
}
});
};
// The issue is here
const getdata = async (req, res) => {
try {
console.log('yes');
const photo = await photo.find({ photo: req.photo.id });
res.json(photo);
} catch (error) {
return res.status(400).json({
error: 'not find',
});
}
};
//router
app.post('/userdashboard', userData);
app.get('/getdata', getdata);
app.listen(port, () => {
console.log(`Dashboard Backend listening on port ${port}`);
});
This is my modelschema
const mongoose = require('mongoose');
const { Schema } = mongoose;
const PhotoSchema = new Schema({
name:{
type:String,
trim:true,
required:true
},
email:{
type:String,
trim:true,
required:true
},
photo:{
data:Buffer,
contentType:String
},
mno:{
type:Number,
required:true
}
});
module.exports=mongoose.model('photo',PhotoSchema);
First mistake you did was not adding console.error(error), if you did it would have shown exact error message.
In this case req.photo is undefined and you are trying to access id property of undefined which causes error to be thrown.
const getdata = async (req, res) => {
try {
const { photo } = req.body
// TODO: use custom error class for validation errors instead of default Error class
if (!photo) throw new Error('photo is missing')
if (!photo.id) throw new Error('photo.id is missing')
// TODO: validate photo.id is valid monogoid
const photos = await photo.find({ photo: photo.id })
res.json(photos)
} catch (error) {
console.error(error) // <-- this was missing
res.status(400).json({ error: 'not find' }) // provide good error message
return
}
}
I am trying to use 'POST' to create a new movie data with using MongoDB. but when I use 'postman' to post my data it kepts saying like this
{"message":"Operation movies.insertOne() buffering timed out after 10000ms"}
I will post three javascript files please let me know about my problem.
First : index
Second : movie(module)
Third : routes
const router = express.Router();
const Movie = require('./models/movie');
//Fetch all movies
router.get("/movies", async (req, res) => {
try {
const movies = await Movie.find();
res.send(movies)
} catch(err) {
return res.status(500).json({message: err.message});
}
})
// Add movie
router.post("/movies", async (req, res) => {
const movie = new Movie({
title: req.body.title,
director: req.body.director,
year: req.body.year
});
try {
const newMovie = await movie.save();
res.status(201).json({ newMovie });
} catch(err) {
return res.status(500).json({ message: err.message });
}
})
module.exports = router;
//from here is Movie.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var MovieSchema = new Schema(
{
title: {type: String, required: true, maxlength: 150},
director: {type: String, required: true, maxlength: 200},
year: {type: Number, required: true}
}
);
//Export model
module.exports = mongoose.model('Movie', MovieSchema);
// from here is routes.js
const express = require('express');
const router = express.Router();
const Movie = require('./models/movie');
//Fetch all movies
router.get("/movies", async (req, res) => {
try {
const movies = await Movie.find();
res.send(movies)
} catch(err) {
return res.status(500).json({message: err.message});
}
})
// Add movie
router.post("/movies", async (req, res) => {
const movie = new Movie({
title: req.body.title,
director: req.body.director,
year: req.body.year
});
try {
const newMovie = await movie.save();
res.status(201).json({ newMovie });
} catch(err) {
return res.status(500).json({ message: err.message });
}
})
enter code here
module.exports = router;
I feel this is so hard to understand lol
Try to refactor your code like this:
router.post("/movies", async (req, res) => {
try {
let newMovie = await Movie.create(req.body);
res.status(201).json(newMovie);
} catch(err) {
return res.status(500).json({ message: err.message });
}
})
In the provided code I don't see you that you are connecting to the database using mongoose.connect for example:
mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true, useUnifiedTopology: true});
Link for the docs.
I am making full stack app and learn from tutorials and videos . I have a problem with GET request to get information about user which is login in the system. I use Postman to check the requests. When I add user with /login , the Postman look user's accesstoken code. I copy his code and paste it in authorization key in headers in Postman and when I change the URL in localhost to /infor to get information about this user and send it. But it say me "Invalid Authentication". I can't find the wrong. I think the problem is in controllers/userCtrl.js in getUser function. Can you help me?
I put the code:
server.js
require('dotenv').config()
const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const fileUpload = require('express-fileupload')
const cookieParser = require('cookie-parser')
const app = express()
app.use(express.json())
app.use(cookieParser())
app.use(cors())
// Use temp files instead of memory for managing the upload process.
app.use(fileUpload({
useTempFiles: true
}))
// Routes
app.use('/user', require('./routes/userRouter'))
// Connect to Mongodb
const URL = process.env.MONGO_URL
mongoose.connect(URL,{
useCreateIndex: true,
useFindAndModify: false,
useNewUrlParser: true,
useUnifiedTopology: true
}, err =>{
if(err) throw err;
console.log('Connected to MongoDB')
})
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log('Server is running on port', PORT)
})
.env
MONGO_URL = ***********
ACCESS_TOKEN_SECRET = ***********
REFRESH_TOKEN_SECRET = *************
routes/userRouter.js
require('dotenv').config()
const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const fileUpload = require('express-fileupload')
const cookieParser = require('cookie-parser')
const app = express()
app.use(express.json())
app.use(cookieParser())
app.use(cors())
// Use temp files instead of memory for managing the upload process.
app.use(fileUpload({
useTempFiles: true
}))
// Routes
app.use('/user', require('./routes/userRouter'))
// Connect to Mongodb
const URL = process.env.MONGO_URL
mongoose.connect(URL,{
useCreateIndex: true,
useFindAndModify: false,
useNewUrlParser: true,
useUnifiedTopology: true
}, err =>{
if(err) throw err;
console.log('Connected to MongoDB')
})
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log('Server is running on port', PORT)
})
models/userModel.js
const mongoose = require('mongoose')
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true,
},
role: {
type: Number,
default: 0
},
cart: {
type: Array,
default: []
}
}, {
timestamps: true
})
module.exports = mongoose.model('Users', userSchema)
middleware/auth.js
const jwt = require('jsonwebtoken')
const auth = (req, res, next) => {
try{
const token = req.header("Authorization")
if(!token) return res.status(400).json({ msg: "Invalid Authentication" })
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if(!err) return res.status(400).json({msg: "Invalid Authentication" })
req.user = user
next()
})
} catch (err) {
return res.status(500).json({msg: err.message})
}
}
module.exports = auth
controllers/userCtrl.js
const Users = require('../models/userModel')
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')
const userCtrl = {
register: async (req, res) => { // async before a function means one simple thing: a function always returns a promise.
try{
const { name, email, password } = req.body
const user = await Users.findOne({ email }) // wait until the promise resolves
if(user) return res.status(400).json({msg: "The email already exists"})
if(password.length < 6)
return res.status(400).json({msg: "Password is at least 6 characteres long."})
//Password encryption
const passwordHash = await bcrypt.hash(password, 10)
const newUser = new Users({
name, email, password: passwordHash
})
// save mongodb
await newUser.save()
//then create jsonwebtoken to authentication
const accesstoken = createAccessToken({ id: newUser._id })
const refreshtoken = createRefreshToken({ id: newUser._id })
res.cookie('refreshtoken', refreshtoken, {
httpOnly: true,
path: '/user/refresh_token'
});
res.json({accesstoken})
} catch(err){
return res.status(500).json({msg: err.message})
}
},
login: async (req, res) => {
try{
const {email, password} = req.body;
const user = await Users.findOne({email})
if(!user) return res.status(400).json({msg: "User does not exist."})
const isMatch = await bcrypt.compare(password, user.password)
if(!isMatch) return res.status(400).json({msg: "Incorrect password"})
// if login success, create access token and refresh token
const accesstoken = createAccessToken({ id: user._id })
const refreshtoken = createRefreshToken({ id: user._id })
res.cookie('refreshtoken', refreshtoken, {
httpOnly: true,
path: '/user/refresh_token'
});
res.json({accesstoken})
} catch(err){
return res.status(500).json({msg: err.message})
}
},
logout: async (req, res)=> {
try{
res.clearCookie('refreshtoken', {path: '/user/refresh_token'})
return res.json({msg: "Logged out"})
}catch(err){
return res.status(500).json({msg: err.message})
}
},
refreshToken: (req, res) => {
try{
const rftoken = req.cookies.refreshtoken
if(!rftoken) return res.status(400).json({msg: "Please login or Register"})
jwt.verify(rftoken, process.env.REFRESH_TOKEN_SECRET, (err, user) => {
if(err) return res.status(400).json({msg: "Please login or Register"})
const accesstoken = createAccessToken({id: user.id})
res.json({ accesstoken })
})
}catch (err) {
return res.status(500).json({msg: err.message})
}
},
getUser: async (req, res) => { // problem
try{
const user = await (await Users.findById(req.user.id)).isSelected('-password')
if(!user) return res.status(400).json({ msg: "Useer does not exist."})
res.json(req.user)
}catch (err) {
return res.status(500).json({msg: err.message})
}
}
}
const createAccessToken = (user) => {
return jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '1d' })
}
const createRefreshToken = (user) => {
return jwt.sign(user, process.env.REFRESH_TOKEN_SECRET, { expiresIn: '7d' })
}
module.exports = userCtrl
For your middle ware for getting the token (auth function)
const { authorization } = req.headers
if (!authorization) {
console.log('[No Authorization Code]');
return res.status(401).send({ message: 'Unauthorized' });
}
if (!authorization.startsWith('Bearer')) {
console.log('[Authorization need to start with Bearer]')
return res.status(401).send({ message: 'Unauthorized' });
}
const split = authorization.split('Bearer ')
if (split.length !== 2) {
console.log('[Invalid Authorization Param')
return res.status(401).send({ message: 'Unauthorized' });
}
const token = split[1] //this is your token to use with jwt.verify
When you sending the token in postman, select Bearer Token
When you start creating your frontend, the codes should be equivalent to the following fetch request
fetch('/api/path', { method: 'GET', headers: { "Authorization": `Bearer ${token}`}}).(res => res.json())
May change method to your desire method (e.g get or post), and the token will be the the jwt token
I saw a similar question posted Here, but they are using MEAN-Stack.
I am currently just using a 'setTimeout' function to wait a few seconds before requesting new data from the server using a fetch api to give it time to update but this doesnt feel like the right way to do it. Is there a simple way for the front-end to update only after the database is updated in Express? I am new to Node please forgive me.
app.js:
const express = require('express');
const app = express();
const mysql = require('mysql');
let viewData = {
//html data
}
var pool = mysql.createPool({
connectionLimit : 10,
host: "localhost",
port: 3306,
database: 'testing',
user: "root",
password: "pass"
});
function sql(type) {
if(type == 'select') {
//Select query here
}
if(request == 'addRow') {
//Insert query here
}
}
app.get(`/`, function (req, res) {
res.sendFile('./views/index.html', {root: __dirname});
})
app.post('/api/add', function(req, res){
res.setHeader('Content-Type', 'application/json');
sql('addRow')
});
app.get('/api/viewData', function (req, res) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(viewData));
})
index.js:
function loadData() {
fetch('/api/viewData')
.then(z => z.json())
.then(a => {
//update html
})
}
function postData(a) {
fetch('/api/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
//data to send to app.js
})
}).then(setTimeout(function(){loadData();}, 3000))
}
You should use async and await function
Example: After async/await
async function fun1(req, res){
let response = await request.get('http://localhost:3000');
if (response.err) { console.log('error');}
else { console.log('fetched response');
}
The complete code of our example is shown below:
npm install express jsonschema body-parser promise-mysql
var express = require('express');
var bodyParser = require('body-parser')
var app = express();
var validate = require('./validate')
var mysqlConnection = require('./connectionShare');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const addItem = function(item, connection){
console.log("Adding Item");
return new Promise(function(resolve, reject){
connection.query("INSERT INTO product SET ?", item)
.then(function(result){
resolve(item.seller);
}).catch(function(error){
reject(error);
});
})
}
const findOrCreateUser = function(user,connection){
console.log("Finding User");
return new Promise(function(resolve,reject){
connection.query("SELECT * FROM user WHERE email=" + connection.escape(user.email))
.then(function(results){
if(results.length == 1){
resolve(results[0].id)
} else {
connection.query("INSERT INTO user SET ?", user)
.then(function(results){
resolve(results.insertId);
});
}
}).catch(function(error){
reject(error);
})
})
}
const selectUserItems = function(userID,connection){
console.log("Selecting Items " + userID);
return new Promise(function(resolve,reject){
connection.query("SELECT * FROM product WHERE seller = " + connection.escape(userID))
.then(function(results){
resolve(results);
}).catch(function(error){
reject(error);return;
});
})
}
app.post('/add/product', validate.JsonValidation, mysqlConnection.getConnection, async function(req,res){
var connection = req.connection;
var item = {
name: req.body.name,
price: req.body.price,
width: req.body.width,
height: req.body.height,
added: req.body.added,
image: req.body.image
};
var user = {
username: req.body.seller.username,
email: req.body.seller.email,
votes: req.body.seller.votes
};
try {
item.seller = await findOrCreateUser(user,connection);
var user_id = await addItem(item,connection);
var items = await selectUserItems(user_id, connection);
connection.connection.release();
res.status(200).json(result);
} catch(error) {
res.status(500).end(error);
}
});
process.on('uncaughtException', error => console.error('Uncaught exception: ', error));
process.on('unhandledRejection', error => {console.error('Unhandled rejection: ', error));
app.listen(8000, function () {
console.log('App listening on port 8000')
});
I am making an iOS project which uses Stripe. I am using a STPCustomerContext and the parameter to create an instance is an object of MainAPI below. When I create the instance, it automatically calls createCustomerKey() but an error (404) is throwing. The URL is "http://localhost:1337/ephemeral_keys" and I believe that is what I have everywhere but yet it is throwing a 404. Here is the code for MainAPI.swift, index.js, & api.js.
The code is:
MainAPI.swift
class MainAPI:NSObject, STPEphemeralKeyProvider {
// override init(){}
static let shared = MainAPI()
var baseURLString = Constants.BASE_URL
// MARK: STPEphemeralKeyProvider
enum CustomerKeyError: Error {
case missingBaseURL
case invalidResponse
}
func createCustomerKey(withAPIVersion apiVersion: String, completion: #escaping STPJSONResponseCompletionBlock) {
// the request
func request(id: String) {
print("creating a eph key request with customerId: \(id)") // good
let url = self.baseURLString.appending("/ephemeral_keys")
Alamofire.request(url, method: .post, parameters: [
"api_version": apiVersion,
"customerId": id
])
.validate(statusCode: 200..<300)
.responseJSON { responseJSON in
switch responseJSON.result {
case .success(let json):
print("created customer ephemeral key!")
completion(json as? [String: AnyObject], nil)
case .failure(let error):
print("could not customer ephemeral key!\n Error info: ")
print(error.localizedDescription)
completion(nil, error)
}
}
}
print("attempting to create customer ephemeral key . . .(createCustomerKey())")
let customerId = . . . // get customer id
request(id: costumerId) // this passes on the CORRECT customerId each time
}
}
api.js
var express = require('express')
var router = express.Router()
var stripe_key = process.env.STRIPE_KEY || "sk_test_myTestKey"
var stripe = require('stripe')(stripe_key);
var request = require("request-promise-native")
//API
router.get('/', function (req, res) {
res.status(200).send(JSON.stringify({ message: 'API Gateway', success: true, error: null }));
}) // Just for testing, just for error-handling
//1. Create a customer account
router.post('/new_customer', function (req, res) {
console.log("Creating new customer account...")
var body = req.body
stripe.customers.create({ email: body.email, })
.then((customer) => {
console.log(customer)
// Send customerId -> Save this for later use
res.status(200).send(JSON.stringify({ success: true, error: null, customerId: customer.id }));
})
.catch((err) => {
console.log(err)
res.status(400).send(JSON.stringify({ success: false, error: err }))
});
})
//2. Save Credit Card with token
router.post('/new_card', function (req, res) {
var customerId = req.body.customerId
var token = req.body.token
stripe.customers.update(customerId, { source: token })
.then((customer) => {
console.log(customer)
res.status(200).send(JSON.stringify({ success: true, error: null }));
})
.catch((err) => {
console.log(err)
res.status(400).send(JSON.stringify({ success: false, error: err }))
});
})
//3. Use customerId to post a charge
router.post('/new_charge', function (req, res) {
var customerId = req.body.customerId
var amount = req.body.amount
var source = req.body.source
stripe.charges.create({
amount: amount, //in cents
currency: "usd",
customer: customerId, //CUSTOMER_STRIPE_ACCOUNT_ID
source: source, // obtained with Stripe.js
}).then((charge) => {
res.status(200).send(JSON.stringify({ message: 'Sucess.', success: true, error: null }));
}).catch((error) =>{
res.status(400).send(JSON.stringify({ message: 'Error', success: false, error: error }));
})
})
// here is the error I am assuming
router.post('/ephemeral_keys', (req, res) => {
const stripe_version = req.body.api_version;
var customerId = req.body.customerId;
if (!stripe_version) {
res.status(400).end();
return;
}
console.log(stripe_version)
// This function assumes that some previous middleware has determined the
// correct customerId for the session and saved it on the request object.
stripe.ephemeralKeys.create(
{customer: customerId},
{stripe_version: stripe_version}
).then((key) => {
console.log("Ephemeral key: " + key)
res.status(200).json(key);
res.status(200).send(JSON.stringify({ message: 'AAAAhh', success: true, error: null }));
}).catch((err) => {
console.log("Ephemeral key error: " + err)
res.status(200).send(JSON.stringify({ message: 'ABBBBBB', success: true, error: null }));
res.status(500).end();
});
});
module.exports = router;
index.js
//Environment Vars
var uri = process.env.NODE_ENV || "development"
console.log(uri + " environment")
//Express App
var express = require('express');
var app = express();
//Api for reading http post request body in express
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
//Log Connections
app.use(function timeLog (req, res, next) {
console.log('incoming connection . . . ')
next()
})
//API middelware
var api = require('./api')
app.use('/api', api)
app.get('/', function (req, res) {
res.status(200).send(JSON.stringify({ message: 'Welcome!', success: true, error: null }));
});
//Create Server
var port = process.env.PORT || 1337;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function () {
console.log('server running on port ' + port + '.');
});
When I create a STPCustomerContext (like this):
let apiKeyObject = MainAPI.shared
customerContext = STPCustomerContext(keyProvider: apiKeyObject)
The following error prints (not allowing the STPPaymentContext later to display):
Response status code was unacceptable: 404.
Please try with the below nodejs code, because syntax which your code is using might not be correct, I was using the same code as you, but later changed the implementation & deployed to firebase CLI
exports.createEphemeralKeys = functions.https.onRequest((req, res) => {
var api_version = req.body.api_version;
var customerId = req.body.customerId;
if (!api_version) {
res.status(400).end();
return;
}
stripe.ephemeralKeys.create(
{ customer: customerId },
{ stripe_version: api_version },
function(err, key) {
return res.send(key);
});
});
You might get below kind of logs.
{
id: 'ephkey_1BramAFjruqsvjkVQGdZLiV5',
object: 'ephemeral_key',
associated_objects: [ { type: 'customer', id: 'cus_CEPMtLbshv7EaP' } ],
created: 1517701830,
expires: 1517705430,
livemode: false,
secret: 'ek_test_YWNjdF8xQmxUb0FGanJ1cXN2amtWLHVPcUdMN3d4UEhncW1sQkNJYmlOdzhwUGdjVUxOd1Y'
}
For .swift file
Please Click here
Please have a look at https://www.youtube.com/watch?v=NdszUvzroxQ
I believe you need to use some remote server, instead of local server,
In my Swift file I am using .responseString instead of .responseJSON by this is I am getting success but the response is a HTML file of requesting Google Signin