Simple Hello World NodeACS Server issue - javascript

I am trying to make a simple NodeACS app in which I want to receive some data in xml format as request from cURL and in Node ACS app after receiving that data I want to send response to client.
My system configurations are:
Node v0.10.13 (x86)
Titanium SDK version: Titanium Studio, build: 3.4.0.201409261227 Build: jenkins-titanium-rcp-master-197 (origin/master)
OS : Windows 7 64 bit
Following is my code files:
application.js:
function index(req, res) {
console.log(req.headers);
req.on('data', function (data) {
console.log("Data received successfully");
});
req.on('end', function () {
res.writeHead(200);
res.end();
});
}
config.json:
{
"routes":
[
{ "path": "/", "method":"POST", "callback": "application#index" }
],
"filters":
[
{ "path": "/", "callback": "" }
],
"websockets":
[
{ "event": "", "callback": ""}
]
}
I'm running my code from command prompt as:
acs run --port 7788
There are no changes made by me in any other file. The issue is when I'm trying to POST XML data via curl using following command :
curl -X POST -d #output.xml http://localhost:7788/
then only headers is getting printed in console as:
D:\GMON-Server\GMON-Server>acs run --port 7788
ACS: Appcelerator Cloud Services Command-Line Interface, version 1.0.20
Copyright (c) 2012-2014, Appcelerator, Inc. All Rights Reserved.
[INFO] No dependencies detected
[INFO] socket.io started
[INFO] ACS started on port 7788
[INFO] { 'user-agent': 'curl/7.39.0',
host: 'localhost:7788',
accept: '*/*',
'content-length': '55580',
'content-type': 'application/x-www-form-urlencoded',
expect: '100-continue' }
and neither the req.on('data') event nor the req.on('end') event is firing.
Please tell me whether there is any configuration issue or there is something wrong with my code?

Related

Error with Gatsby when trying to proxy request

I am getting an error when trying to proxy my dev url through Gatsby. In my gatsby-config.js I have:
proxy: [
{
prefix: '/myaccount',
url: 'https://www-dev.site.com',
},
],
Gatsby Proxy Error Screenshot
Error when trying to proxy request "/myaccount/" to "https://www-dev.site.com/myaccount/" write EPROTO 4584046080:error:14094458:SSL routines:ssl3_read_bytes:tlsv1 unrecognized name:../deps/openssl/openssl/ssl/record/rec_layer_s3.c:1544:SSL alert number 112
RequestError: write EPROTO 4555591168:error:14094458:SSL routines:ssl3_read_bytes:tlsv1 unrecognized name:../deps/openssl/openssl/ssl/record/rec_layer_s3.c:1544:SSL alert number 112
This was working and all of a sudden stopped.
As it has been said, it looks like a certificate issue (because of the SSL). Without more implementation details it's difficult to guess if a proposed solution will work on your scenario but you can try setting the security as false (secure: false) to don't reject self-signed certificates. In your gatsby-config.js:
const { createProxyMiddleware } = require("http-proxy-middleware")
module.exports = {
developMiddleware: app => {
app.use(
"/.netlify/functions/",
createProxyMiddleware({
target: "http://localhost:9000",
secure: false,
pathRewrite: {
"/.netlify/functions/": "",
},
})
)
},
Docs: https://www.gatsbyjs.com/docs/api-proxy/#self-signed-certificates
Tweak it to adapt it to your needs, replacing /.netlify/functions/ for your API endpoint.

Simple LocalServer for test jwt (form register and login request)

Hi i need to do a webapp with user registration and I would like to try the script locally.
I do all site with Vue + Axios and I need to implement jwt.
Can someone let me how i can start locally server for test this script?
import axios from 'axios'
export default {
name: 'Register',
data() {
return {
email: '',
password: '',
nome: '',
cognome: '',
data: '',
telefono: '',
risiedi: '',
cap: '',
provincia: '',
citta: '',
privacy: false
}
},
methods: {
handleSubmit() {
const data = {
email: this.email,
password: this.password,
nome: this.nome,
cognome: this.cognome,
data: this.data,
telefono: this.telefono,
risiedi: this.risiedi,
cap: this.cap,
provincia: this.provincia,
citta: this.citta,
privacy: this.privacy
};
axios.post('http://localhost:8000', data)
.then(
res => {
console.log(res)
}
).catch(
err => {
console.log(err)
}
)
}
}
}
To install a simple Node.js server using Express.js, first ensure that you have express-generator installed on your global npm. You can run the command below to install
npm install -g express-generator // may require (sudo) in some instances
Go to your desired project directory (e.g. cd backend), and make sure it is empty
.
├── frontend
├── backend
Then run the command
npx express-generator
Install the dependencies
npm install
Install cors
npm install cors
Set up cors (Cross Origin Resource Sharing) by opening app.js
// paste this at the top of the file
const cors = require('cors')
// then paste this somewhere after var app = express();
const corsOptions = {
origin: 'http://localhost:<Your_Frontend_Port>',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
/* Enable CORS in the app */
app.use(cors(corsOptions))
Spin your server by running
npm start
You can now access your server by accessing
http://localhost:3000 // this is the default port
You can change the server port by defining a .env file and declaring PORT=<Your_preferred_port> and then running npm install dotenv before pasting require('dotenv').config() at the top of bin/www
You can modify the routes by access routes/index.js or routes/users.js. For example, to return JSON to the client, use response.json({ yourKey: 'Your content' }) or res.send({ name: 'MyName' }). Both .json and .send are almost identical but we'll leave it here, for now.
Let us try an example route. Go to routes/index.js and add a route
/* GET name page */
router.get('/test', function(req, res, next) {
res.json({ testKey: 'Test content' })
});
On the frontend, do something like
axios.get('http://localhost:3000/test')
.then(res => { console.log(res) })
.catch(err => { console.log(err) })
To make your server reload immediately after making changes, install nodemon on the server
npm install nodemon -D
Go to the package.json and replace "start": "node ./bin/www" with "start": "nodemon ./bin/www"
Stop the server and run npm start once again
For more details, check the express documentation

swagger POST node.js express

I make my GET services work in Swagger (with Node.js), but I am not able to make the POST work. Can someone point out where I am making mistake in below testPost service?
my service definition
"/people/testPost": {
"post": {
"summary": "write the test POST.",
"description": "Test",
"operationId": "myService",
"consumes": [
"application/json"
],
"tags": [
"test"
],
"parameters": [
{
"name":"body",
"paramType":"body",
"description": "body for the POST request",
"required":false
}
]
In service (filename = myService.js), I am trying this
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:true}));
app.post("/people/testPost", function (req, res) {
console.log("I am in the testPost service); //this gets printed
console.log("The req body", req.body) //says 'undefined'
});
Here is my CURL command I use to POST
curl -H "Content-Type: application/json" -X POST -d '{"arg1":"open", "arg2":"IVR","arg3":"", "arg4" :"1234567"}' http://localhost:8016/people/testPost
Any simple POST request that uses Swagger with Node (all I need is how to configure my "body" in the json file) would, hopefully, gets me going
Some one, please, look into my "parameters" and the curl POST and see where I need to make changes/corrections.
because you're receiving JSON request you need an appropriate handler for this. For JSON you should use app.use(bodyParser.json());, see example on module page.
app.use(bodyParser) don't needed btw.

Can't get response data with Oauth2/BaseCamp API

I am an "advanced beginner" with javascript API's so my needs maybe sophomoric, but after pounding my head against the wall all night appreciate any basic guidance you can provide. I am trying to authenticate an app using Oauth2 to hit my BaseCamp site.
I am using Grant Express and have registered my app successfully such that I received client_ID, client_secret and redirect uri. For the redirect uri I added a folder called "auth" but the only thing in it is an index.html file that is blank. So the redirect url is http://example.com/auth.
On my local machine I have created a directory called oauth and within it ran:
npm install express
npm install grant-express
I created a file app.js that looks like this:
var express = require('express')
, session = require('express-session')
var Grant = require('grant-express')
var config = {
server: {
protocol: "http",
host: "127.0.0.1:3000"
},
basecamp: {
key: "key_from_basecamp",
secret: "secret_from_basecamp",
callback: "/basecamp/callback"
}
}
var app = express()
app.use(session({secret:'grant',
resave: true,
saveUninitialized: true}))
app.use(new Grant(config))
app.get("/basecamp/callback", function (req, res) {
console.log(req.query)
res.end(JSON.stringify(req.query, null, 2))
})
app.listen(3000, function () {
console.log('Express server listening on port ' + 3000)
})
The package.json file looks like this:
{
"name": "auth",
"version": "1.0.0",
"description": "",
"main": "app.js",
"dependencies": {
"express": "^4.13.4",
"grant-express": "^3.6.0"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
I go to the terminal and enter node app.js and get the response: Express server listening on port 3000. All good right?
When I go to my browser and type in http://localhost:3000/connect/basecamp the url does redirect to: https://launchpad.37signals.com/authorization/new?client_id=client_id_from_basecamp&response_type=code&redirect_uri=http%3A%2F%2F127.0.0.1%3A3000%2Fconnect%2Fbasecamp%2Fcallback&type=web_server
but the page contains this error: :error: Provided redirect_uri is not approved
If I got to: http://localhost:3000/connect/basecamp/callback
I see this error (also in the console of the server) { error: { error: 'Grant: OAuth2 missing code parameter' } }
In the Basecamp API documentation it says:
Configure your OAuth 2 library with your client_id, client_secret, and redirect_uri. Tell it to use https://launchpad.37signals.com/authorization/new to request authorization and https://launchpad.37signals.com/authorization/token to get access tokens. What is "it" and how, exactly would I tell it to use these urls? Do I add these url's into my app.js file as objects? Or do I go into another file? Do I need to add something into http://example.com/auth?
Not sure where to go from here.... Many thanks for any assistance.
The problem was my redirect url. It should be
http://localhost:3000/connect/basecamp/callback On to new errors!

How to execute node (console) command from javascript file on click via ajax

Im new to node.js and this is my question:
For example: I got web application and from that application I have a button and on button click I want to run node console command (for example: node socket.io).
So:
$( ".button" ).on( "click", function() {
//run ajax to node with command for example "node socket.io"
});
So in this example I want to start socket.io from web javascript file. How to do it ? I know its very basic question but I want to understand how to do it or is it even possible.
EDIT
But is it possible to run ajax request with that node command to node.js and then fire up it up ("node socket.io")?
Im asking this because I want to start and stop socket.io from web application, not from console command directly.
You would need an express route like this:
...
var exec = require('child_process').exec;
app.post('/exec', function(req, res) {
var cmd = req.body.command;
exec(cmd, function(error, stdout, stderr) {
if (stderr || error) {
res.json({
success: false,
error: stderr || error,
command: cmd,
result: null
})
} else {
res.json({
success: true,
error: null,
command: cmd,
result: stdout
})
}
})
})
...
note: stderr and stdout are buffers.
You then need to POST your command (using AJAX or a form) to /exec. Which will give you a response such as:
Success:
{
success: true,
error: null,
command: "ls",
result: "app.js bin node_modules package.json public routes views "
}
Failure:
{
success: false,
error: "/bin/sh: foobar: command not found ",
command: "foobar",
result: null
}
You need to be extremely careful with security having something like this though as you are opening up access to your system's console.

Categories