I'm trying to follow this documentation from Stripe: https://stripe.com/docs/connect/standard-accounts
I'm stuck on point 4 where I am trying to authorize a user and get a response with an access token.
I am using a express backend in a React app and I have the following set up in my server.js file:
const path = require('path');
const express = require('express');
const app = express();
const publicPath = path.join(__dirname, '..', 'public');
var TOKEN_URI = 'https://connect.stripe.com/oauth/token';
var CLIENT_ID = 'xxxx'
var API_KEY = 'STRIPE_API_KEY'
app.use(express.static(publicPath));
app.get('/api/callback', function(req, res) {
var code = req.query.code;
request.post({
url: TOKEN_URI,
form: {
grant_type: "authorization_code",
client_id: CLIENT_ID,
code: code,
client_secret: API_KEY
}
}, function(err, r, body) {
var accessToken = JSON.parse(body).access_token;
console.log(accessToken);
});
});
app.get('*', (req, res) => {
res.sendFile(path.join(publicPath, 'index.html'));
});
I've removed my port number and listening reference but this is in place.
So when I test with Stripe and go my callback page I get an Internal Server Error but I am not sure what is causing this and why I am getting no response back from my console.log?
Thanks.
I think you need to import the request library at the top
const request = require('request');
Also please make sure your package.json file contains request library if not please install it first. https://www.npmjs.com/package/request
Related
hello i have a issue i build a project when i start to add the server side
i am using node js express
i create fetch post to spesific url from the database (mongoDB)
and i want to add the users
now
its workd but i try to reconfigure the files and using router and now i get 404 when i try to make the post is upload some code
just need to know where is the bad request
the url i want to fetch is
http://localhost:5000/shopping-cart/user/sign-up
Axios.post("http://localhost:5000/shopping-cart/user/sign-up", user).then((response) => {
console.log(response);
});
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const path = require("path")
const productRouter = require("./routes/product.route");
const userRouter = require("./routes/user.route");
const { setServerConfiguration } = require("./config");
setServerConfiguration(app);
mongoose.connect('mongodb://localhost/shopping-cart-data-base');
app.use("/shopping-cart", productRouter);
app.use("/user/sign-up", userRouter);
app.listen(5000);
const router = require('express').Router();
const errorsHandler = require('../utils/errorsHandler');
const UserModel = require('../models/User');
router.post("/user/sign-up", async (req, res) => {
let body = req.body;
console.log(body)
try{
await UserModel.create({
name: body.name,
username: body.username,
password: body.password,
shoppingHistory: [],
});
res.send(body);
}catch(e){
return errorsHandler(e, req, res);
}
});
module.exports = router;
Your router is mounted on the /user/sign-up prefix:
app.use("/user/sign-up", userRouter);
Which means that all requests that start with /user/sign-up will get passed to your router.
Your router should be routing relative to that prefix, so to make it work, use this:
router.post('/', ...)
Try this url
"http://localhost:5000/user/sign-up"
If you want to use "http://localhost:5000/shopping-cart/user/sign-up" than you need to define route like that, for example:
router.post("shopping-cart/user/sign-up", async (req, res) => {
//Your code
})
404 route not found
app.use("/shopping-cart", productRouter) => route1
app.use("/user/sign-up", userRouter); => route2
route1 other route2
url http://localhost:5000/shopping-cart request route1
url http://localhost:5000/user/sign-up request route2
I've just started learning Express and Servers.
Problem
Just wanted to load another EJS page onto my localhost:4000/ path as a response after a POST request has been made for a form.
However, although I do get the response of the EJS page with the data from the req.body in the form from the client-side. I can't seem to get the page to load on the browser.
Any ideas? pls help
Express.js Server
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
let path = require('path');
let fs = require('fs');
var urlencodedParser = bodyParser.urlencoded({extended:true});
app.use(express.json());
app.set('view engine', 'ejs');
app.use('/', express.static(__dirname + '/views'));
app.use('/', express.static(__dirname + '/views/partial'));
//Handling the GET request with the render of EJS file "index"
app.get('/', (req, res)=> {
res.render('index');
});
//Handling the POST request from the client, and sending the EJS file "createAccount" as a response
app.post('/', urlencodedParser, (req, res) => {
res.set('cache-control', 'max-age=0; private; no-cache');
res.render('createAccount', {data:req.body}); //
});
app.listen(4000, ()=>{
console.log('Port 4000 has been called');
});
EDIT:
I've included the JS file which I am using to make the POST request below.
document.querySelector('#btn').addEventListener('click', Master);
async function Master(){
console.log("Button clicked")
const username = document.querySelector("#username").value;
const password = document.querySelector("#password").value;
let results = {
"username": username,
"password": password
};
console.log(results);
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(results)
};
const post = await fetch('/', options);
};
I don't know if this is a correct question lol but is it ok to have the same "/" in get and post request? Why not put something in it.
app.post("/create")
then also change this
const post = await fetch('/create', options);
Is there a way to intercept a http call before the csurf validation. I have the below code
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
var bodyParser = require('body-parser')
var express = require('express')
// create express app
var app = express()
// create api router
var api = createApiRouter()
// mount api before csrf is appended to the app stack
app.use('/api', api)
// now add csrf and other middlewares, after the "/api" was mounted
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(csrf({ cookie: true }))
app.get('/form', function (req, res) {
// pass the csrfToken to the view
res.render('send', { csrfToken: req.csrfToken() })
})
app.post('/process', function (req, res) {
res.send('csrf was required to get here')
})
function createApiRouter () {
var router = new express.Router()
router.post('/getProfile', function (req, res) {
res.send('no csrf to get here')
})
return router
}
I want to log the CSRF token sent by the client for troubleshooting an error I am getting. But I was not able to find a way to intercept the request before it is sent for CSRF validation.
I was able to do it by adding the following code
var logToken = function (req, res, next) {
console.log('Token: ', res.get('x-xsrf-token');
next();
};
app.use(logToken);
I added this code before configuring the csrf token and after configuring the cookie parser.
Wanting a Node router that POST Json to some remote API?
I put a lot of effort into this issue this morning so I wanted to share this by offering some comprehensive examples for your benefit.
In each example the router has a GET method that when called, POSTS back to the same router. I'm also showing, very clearly, how to send AND how to access the received data.
In Node.js, in a router, you might sometime what to post from the router to some remote api.
--- using npm install needle -save --- the file routes/nee.js ---
var express = require('express');
var router = express.Router();
var needle = require('needle');
router.get('/', function (req, resp) {
var dat = { theGreatest: 'ChuckBerry' };
var lookbackURL = 'http://' + req.headers.host + req.baseUrl;
needle.post(lookbackURL, dat, { json: true });
resp.redirect('/');
});
router.post('/', function (req, resp, next) {
console.log('body.theGreatest', req.body.theGreatest);
resp.sendStatus(200);
});
module.exports = router;
--- using npm install request -save --- the file routes/req.js ---
var express = require('express');
var router = express.Router();
var request = require('request');
router.get('/', function (req, resp) {
var dat = { theGreatest: 'ChuckBerry' };
var lookbackURL = 'http://' + req.headers.host + req.baseUrl;
request.post(lookbackURL, { json: dat });
resp.redirect('/');
});
router.post('/', function (req, resp, next) {
console.log('body.theGreatest', req.body.theGreatest);
resp.sendStatus(200);
});
module.exports = router;
--- using Node's very own http.request() -- the file routes/nodehttp.js ---
--- When you only want to POST some Json data make your life simpler by instead doing a PUT of the content-type=application/json -----
var express = require('express');
var router = express.Router();
var http = require('http');
router.get('/', function (req, resp) {
var hst = req.headers.host.split(':');
var dat = { theGreatest: 'ChuckBerry' };
var bdy = JSON.stringify(dat); // you have to take care of this for yourself
var options = { host: hst[0], port: hst[1], path: req.baseUrl, method: 'PUT' //PUT!
, headers: { 'Content-Type': 'application/json' }
};
var r = http.request(options);
r.write(bdy);
r.end();
resp.sendStatus(200);
});
router.put('/', function (req, resp) { // PUT. it's a PUT not a POST
console.log('body[\'theGreatest\']', req.body['theGreatest']); // But here you DON'T have to parse it for yourself.
// ^ I'm happy for that even if I am feeling the loss of symmetry.
// ^^ At the same this is why your life is easier in a PUT instead of a POST.
resp.sendStatus(200);
});
module.exports = router;
And perhaps the easiest of all
--- using npm install requestify -save --- the file routes/rify.js ---
var express = require('express');
var router = express.Router();
var requestify = require('requestify');
router.get('/', function (req, resp) {
var lookbackURL = 'http://' + req.headers.host + req.baseUrl;
requestify.post(lookbackURL, {
theGreatest: 'ChuckBerry'
})
.then(function (res) {
//res.getBody(); // JSON parsed or XML object
//res.body; // or get the raw
res.redirect('/');
});
});
router.post('/', function (req, resp, next) {
console.log('body.theGreatest', req.body.theGreatest);
resp.sendStatus(200);
});
module.exports = router;
Enjoy & I hope these more comprehensive demonstrations help you too.
Looks good. Quite a bit of effort documenting the different options.
A little later I'm going to add a Requestify.js example. Stay tuned and look for it above
I'm just now started to learn Node and Express, I have some probelm with the routes in express. I want a well modular code for routing. I want to query some data from mysql database:
Here is my app.js(it is on "public_html" directory):
var path = require('path');
var express = require('express');
var routes = require('./routes');
var app = express();
var staticPath = path.resolve(__dirname, './');
app.use(express.static(staticPath));
routes.init(app);
module.exports = app;
app.listen(3000, function() {
console.log('Server is listening on port: 3000');
});
Next file: "public_html/routes/index.js":
exports.init = function(app){
//electronics routes
app.use('/laptop', require('./laptop'));
};
"public_html/routes/laptop/index.js":
var router = require('express').Router();
router.get('/laptop', require('./modules/laptop'));
module.exports = router;
"public_html/routes/laptop/modules/laptop.js":
var mysql = require('mysql');
var connection = mysql.createConnection(
{
host : 'localhost',
user : 'admin',
password : 'xxxxxxx',
database : 'database',
}
);
module.exports = function(req, res){
connection.connect();
var queryString = 'SELECT * FROM laptop';
connection.query(queryString, function(err, rows, fields) {
if (err) throw err;
res.writeHead(200, { 'Content-Type': 'application/json'});
res.end(JSON.stringify(rows));
});
connection.end();
};
I want to keep this modularity even if its look like a bit over complicated, in the future I will need it.
So the problem is it's just doesn't working, I think its just a stupid error somewhere, but I don't find it and on the internet there is only simple route examples so I cant use them in this case.
The problem is most likely in your routing.
You're mounting a separate router at /laptop. Within that mounted router you're setting up a /laptop (GET) route on top of that, so the full path would be /laptop/laptop.