Currently, I have run into an issue that I've been stuck on all day. In essence, I am trying to get a login session for an account through the Roblox authentication API. It works the first when I post from my server to their API so that I can get the X-CSRF-TOKEN which needs to be set in the headers for the next time I make a post to the same API so I am able to get the .ROBLOSECURITY which is used to authenticate that the account session. However, the second time I post to their API with the token in the header, I get a 400 error and I am unsure of why this is occurring.
Also, for anyone who is wondering, it is returning a valid X-CSRF-TOKEN.
var request = require('request');
var loginOptions = {
url: 'https://auth.roblox.com/v2/login',
form: {
'ctype': 'Username',
'cvalue': 'AccountUsernameHere',
'password': 'AccountPassGoesHere'
},
headers: {
'Content-Type': 'application/json'
}
};
request.post(loginOptions, function(error, response, body) {
loginOptions.headers['X-CSRF-TOKEN'] = response.headers['x-csrf-token'];
request.post(loginOptions, function(error, response, body) {
if (response.statusCode == 200) {
console.log('Success: ' + body);
} else {
console.log(response.statusCode + ' : ' + response.statusMessage);
}
});
});
You need install cors in nodejs: npm install cors, you can try the following below
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
It appears there were two issues with my code.
The first issue is that I was using form when I should have been using body. I also ended up needing to add json: true too.
Related
Basically I am coding a bot for this website which requires logging into your steam account and I am unsure of why this does not work as I am using the request module in node.js to send a request to the login page which once your username and password are entered it should redirect to the site and then I can do what I want to do next. Currently the code I provided below shows "Upload successful!" when run but if I put in an invalid username and password it still is successful which I would like to change which I am unsure of how to make the request fill the input field of the form and complete the form.
I have looked at other posts on Stackoverflow but haven't found any that have worked/are the same area I need.
const express = require('express')
const app = express()
const port = 3000
app.listen(port, () => console.log(`Listening at http://localhost:${port}`))
var urlWithLoginForm = 'https://steamcommunity.com';
var loginUrl = urlWithLoginForm+'/openid/login?openid.mode=checkid_setup&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.return_to=https%3A%2F%2Fapi.entertoroll.com%2Fauth%2Fsteam%2Freturn&openid.realm=https%3A%2F%2Fapi.entertoroll.com';
var formData = {'username': 'your_username', 'password': 'your_password'};
request(urlWithLoginForm, function() { // initialising cookies by doing http get
// so now we have cookies in jar, now we can make post request
request.post({url: loginUrl, formData: formData}, function(err, res, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful!');// Server responded with:', body);
app.get('/', (req, res) => res.send(body))
});
});
The part where it puts it on localhost was just for my testing so I could see if it got the page correctly/what the request looks like live.
I am trying to make POST request for OTP using Node.Js Express. Below is the code for making post request using request but I want to make post request using Express.
const request = require('request');
const options = {
method: 'POST',
url: 'https://d7-verify.p.rapidapi.com/send',
headers: {
'content-type': 'application/json',
authorization: 'undefined',
'x-rapidapi-key': 'e47df3d7e5msh868bdee0049d425p19',
'x-rapidapi-host': 'd7-verify.p.rapidapi.com',
useQueryString: true
},
body: {
expiry: 900,
message: 'Your otp code is {code}',
mobile: 971562316353,
sender_id: 'SMSInfo'
},
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
How can I make above request in Express framework?
Express, is a back end web application framework for Node.js. To receive such requests using Express.js the following code will be helpful
var express = require('express')
var app = express()
// POST method route
app.post('/sendotp', function (req, res) {
//Generate OTP
var otp=Math.floor(100000 + Math.random() * 900000);
//Get Mobile number from response body
var mobile=req.body.mobile;
//Then send OTP to respective mobile number
// send sucess message to use
res.send('OTP Sent Successfully')
})
I am not able to get the data in the http post method of express nodejs.I am posting data from angular2. When i inspect in the network section of chrome, the payload is visible but the same data is received blank at app.post method.Please help me.
angular2 code
this.headers = new Headers();
this.headers.append('Content-Type', 'x-www-form-urlencoded');
let body = JSON.stringify({name:"Lionel Messi"});
return this.http
.post('http://localhost:8081/save',body
,this.headers);
}
nodejs code
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/save', function (req, res) {
console.log("Got a POST request for the homepage");
console.log(req.body);// output - {}
res.send('Hello POST');
})
Network Section in Chrome....payload is proper
alert method in node.js will not work . You need to use console.log("Hello");
Second thing is to get body data , use req.body.name
My way of writing code is like below and it works
$http({
method: 'POST',
url: 'http://localhost:8081/save',
data: {name:"Lionel Messi"}
})
.success(function(data) {
return data
})
.error(function(error) {
// handle error
});
Other way you can try is:
$http.post('http://localhost:8081/save', {name:"Lionel Messi"})
.then(function(data) {return data})
.catch(function() {console.log("Error Occured");});
You can do it like this-
Suppose you have sent username and password from your browser by post method.
app.post("/ url,function(request,response)
{ var username=request.body.username;
var password=request.body.password;})
I have issue with posting data from angular2 frontend api to backend client - nodeJS + mongoose.
On Angular2 client I make console.log using data, which I'am sending, and service display correct values.
On NodeJS backend I try also to console.log posted data, but I got undefined. Please look at code below, and try to figure out what I make wrong. I tried to this also with Promise<> and Observable<>, with same effect.
PS. GET data from NodeJS api via Angular 2 is working well.
PS2. Important fact, Problem exist, because angular2 doesnt make a headers in post or put. Every time, when I make POST Req, NODE Server logs OPTION /login. What that's mean?
Angular2:
signIn(data: Object): Observable<User> {
let bodyString = JSON.stringify(data);
let headers = new Headers({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
});
let options = new RequestOptions({ headers: headers });
console.log("data: ", data, "\nbodyString: ", bodyString, "\nHeaders: ", headers, "\nOptions: ");
return this.http
.post( this.signInUrl, bodyString, {headers: headers})
.map( (res:Response) => res.json() )
.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
NodeJS:
[...]
// configure app
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var mongoose = require('mongoose');
var Test = require('./model/test');
var User = require('./model/user.schema');
mongoose.connect('mongodb://localhost:27017/lounge');
app.set('secret', config.secret);
app.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
app.post('/login', function (req, res) {
console.log("Recived login request!", req.body);
});
[...]
I think your problem is how you are making the post request by not using the RequestOptions object you created.
signIn(data: Object): Observable<User> {
let bodyString = JSON.stringify(data);
let headers = new Headers({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
});
let options = new RequestOptions({ headers: headers });
console.log("data: ", data, "\nbodyString: ", bodyString, "\nHeaders: ", headers, "\nOptions: ");
return this.http
.post( this.signInUrl, bodyString, options) // **Change happens here
.map( (res:Response) => res.json() )
.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
The only change is using the options (RequestOptions) you declared instead of trying to define "{ headers: headers }" in the post method.
This is my first time post. I hope this helped and this posts correctly.
I think problem is at nodejs and angular cominication. Because they work on different port they can not comminicate. So you should add this code to nodejs as middleware and also ı recommend you to search "cors express" and "cors npm package". I hope this solve your problem.
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
I'm using a combination of Express and Request (installed using npm) to try to send a get request to get some json from the server. However no matter what I do the body that is returned is "undefined".
This is the code in my server.js file. The json isn't actually what I'm sending, it's just an example as I can't post what I'm actually sending.
import express = require("express");
import bodyParser = require("body-parser");
let app = express();
app.use(bodyParser.json());
app.get('/config', function(req, res){
res.json('{name: test}');
})
app.listen(3000);
I've tried both of the following but both of them say that body is undefined.
import request = require("request");
let req = {
url: `http://localhost:3000/config`,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
request(req, function(error, response, body){
this.config = JSON.parse(body);
})
request(`/config`, function(err, res, body) {
this.config = JSON.parse(body);
});
Does anyone know what I'm doing wrong? I've never used express or request before so any tips would be greatly appreciated.
UPDATE
If I change the request code to the following, the inside of the function is never run. Does anyone know why this would be?
let req = {
url: `http://localhost:3000/config`,
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
}
request(req, function(error, response, body){
console.log("response => "+JSON.parse(body));
return JSON.parse(body);
})
Since OP hasn't got it working and I believe the code he got up there is correct. I may as well post my working solution here to help him get started.
Hopefully this will save you hours of debugging...
Client:
"use strict";
let request = require("request");
let req = {
url: `localhost:4444/config`,
proxy: 'http://localhost:4444',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
request(req, function (err, res, body) {
this.config = JSON.parse(body);
console.log("response => " + this.config);
});
Server:
"use strict";
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
var config = require('config');
app.use(bodyParser.json());
app.get('/config', function(req, res){
res.json('{name: test}');
});
// Start the server
app.set('port', 4444);
app.listen(app.get('port'), "0.0.0.0", function() {
console.log('started');
});
Output:
response => {name: test}
I dont't know if you have posted whole of your server's code, it seems like you missed app.listen(port) so that your server cannot be started up correctly.
Also, if you added if (error) { console.log(error); } at the first line of the callback function of request, you'll find it print an error: [Error: Invalid URI "/config"]
And that's why the body is always undefined: You have to give the full url such like http://localhost:xxxx to request.
In short:
Your server didn't listen to a specific port. app.listen(5678)
Your client didn't know the complete url. request('http://localhost:5678/config', (...)=>{...})