I have a very simple "bot server" that responds to the presented utterance with the same utterance:
const express = require('express')
const app = express()
app.use(express.json())
const port = 3001
app.get('/', (req, res) => res.send('Hello World!'))
app.post('/message', (req, res) => {
res.send({output: req.body.input})
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
Message flow:
me: POST -> http://localhost:3001/message -> { "input": "hi" }
bot: Responds with: { "output": "hi" }
botium.json:
{
"botium": {
"Capabilities": {
"PROJECTNAME": "whatever",
"CONTAINERMODE": "simplerest",
"SIMPLEREST_URL": "http://localhost:3001/message",
"SIMPLEREST_METHOD": "POST",
"SIMPLEREST_BODY_TEMPLATE": "{\"text\": \"{{input}}\"}",
"SIMPLEREST_RESPONSE_JSONPATH": "$.output",
"SIMPLEREST_PING_URL": "http://localhost:3001/"
},
"Sources": {},
"Envs": {
"NODE_TLS_REJECT_UNAUTHORIZED": 0
}
}
}
The emulator browser opens without problems, but the "bot" does not respond..
I misunderstood the docs - body rest template should look like this:
"SIMPLEREST_BODY_TEMPLATE": "{\"input\": \"{{msg.messageText}}\"}",
Where "input" is a the path to the input utterance - by contract with your REST service
The "msg.messageText" is apparently used by botium to know how to access the utterance
Related
I'm trying to run a test suite with mocha, the goal is to start the server beforeEach test case and then
close it afterEach test case.
But for some reason when the afterEach case ignites I get the following error:
Error [ERR_SERVER_NOT_RUNNING]: Server is not running.
The test case passes which means the server is up and running.
I Export the server like this from my app.js file:
var server = app.listen(3000, function () {
var port = server.address().port;
console.log("Example app listening at port %s", port);
});
module.exports = server; // Export server in order to use it in test files
My test file:
describe("loading express", function () {
var server;
before(function (done) {
User.deleteMany(done);
});
beforeEach(function () {
server = require("../app");
});
afterEach(function (done) {
server.close(done);
});
describe("Create user account with valid email address", function () {
describe("Route: POST /signup", () => {
it("201 HAPPY PATH", (done) => {
chai
.request(server)
.post("/signup")
.send({
email: "test23222#test.test",
password: "12345678",
firstname: "testtest",
lastname: "testtest",
})
.end((err, res) => {
res.should.have.status(201);
done();
});
});
});
});
});
I believe I need to export a promise.
This is what I got so far:
var server = new Promise(function (resolve, reject) {
app.listen(3000, function () {
var port = server.address().port;
console.log("Example app listening at port %s", port);
resolve();
});
}
module.exports = server; // Export server in order to use it in test files
in test suite:
var server = require('./app.js')
server.then(function() {
....
}
The server is closed by chai-http every time a request is served.
From the chai-http docs:
If you want to keep the server open, perhaps if youβre making multiple requests, you must call .keepOpen() after .request(), and manually close the server down:
E.g:
chai
.request(server)
.keepOpen() // <-- Here
.post("/signup")
.send({
email: "test23222#test.test",
password: "12345678",
firstname: "testtest",
lastname: "testtest",
})
Hi I would like to send an email to myself from my gatsby site in development. I have tried to follow this guide
I have set up the project like:
/client (gatsby site running on port 8000)
----package.json
server.js (node server running on port 3000)
----package.json
Here is my server.s code:
require("dotenv").config({
path: `.env`,
})
const port = 3000
const bodyParser = require("body-parser")
const express = require("express")
const nodemailer = require("nodemailer")
const morgan = require('morgan')
const app = express()
app.use(morgan('dev'))
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
const contactAddress = "myemail#gmail.com"
const mailer = nodemailer.createTransport({
service: "Gmail",
auth: {
user: process.env.GMAIL_ADDRESS,
pass: process.env.GMAIL_PASSWORD,
},
})
app.get('/', function (req, res) {
res.send('The server is running...')
})
app.post("/contact", function (req, res) {
console.log('post request')
mailer.sendMail(
{
from: req.body.name,
to: [contactAddress],
subject: "Message from website",
html: req.body.message,
},
function (err, info) {
if (err) {
console.log(err)
return res.status(500).send(err)
} else {
//success
console.log('worked')
res.json({ success: true })
}
}
)
})
app.listen(port, () =>
console.log(`Mail server listening on port ${port}!`)
);
The form action is like:
<form css={containerStyle} name="contact" method="post" action="http://localhost:3000/contact">
<FormComponents />
</form>
So far it is not logging to console or sending an email. Any pointers where I am going wrong would help. Thanks.
I solved it. Basically, i didn't understand how express worked - you need to include cors in express. And use Axios to send the form data
Answer here helped me
I'm build vue app, and for mine app need api request to server from client, also necessary proxy any request.
It's mine vue.config.js
const producer = require('./src/kafka/producer');
const bodyParser = require('body-parser')
module.exports = {
devServer: {
setup: function (app, server) {
app.use(bodyParser.json())
app.post('/send-message', function (req, res) {
producer.send(req.body)
.then(() => {
res.json({result: true, error: null});
})
.catch((e) => {
res.status(500).json({result: false, error: e});
})
});
},
proxy: {
'/v2/order/by-number': {
target: 'http://address-here'
}
}
}
};
As you can see so i'm use body-parser app.use(bodyParser.json())
After I added it, proxying stopped working for me. Request to /send-message freezes after show me error
Proxy error: Could not proxy request path-here from localhost:8080
to http://address-here
Internet searches have not led to a solution.
For a long time, i find a solution:
Add second param jsonParser to app.post()
See full example
const producer = require('./src/kafka/producer');
const bodyParser = require('body-parser')
const jsonParser = bodyParser.json({limit: '1mb'});
module.exports = {
devServer: {
setup: function (app, server) {
app.post('/send-message', jsonParser, function (req, res) {
producer.send(req.body)
.then(() => {
res.json({result: true, error: null});
})
.catch((e) => {
res.status(500).json({result: false, error: e});
})
});
},
proxy: {
'path': {
target: 'http://address-here'
}
}
}
};
I've managed to have a express + Apollo Backend as a serverMiddleware in Nuxtjs.
Everything works fine(auth, cache, datasources, queries, mutations) but now I'm trying to get subscriptions(websockets) running and its giving me a hard time.
I tried this example https://www.apollographql.com/docs/apollo-server/data/subscriptions/#subscriptions-with-additional-middleware but even letting the httpServer listening didn't work.
This is my API file which I require through the nuxt.config.js with '~/api/index' :
module.exports = async () => {
const app = require('express')()
const server = await require("./apollo")() // apollo-server-express w/ typeDefs and resolvers
// apply Apollo to Express
server.applyMiddleware({ app });
console.log(`π ApolloServer ready at ${server.graphqlPath}`);
const httpServer = http.createServer(app);
server.installSubscriptionHandlers(httpServer);
console.log(`π ApolloSubscriptions ready at ${server.subscriptionsPath}`);
return {
path: '/api',
handler: httpServer
}
}
Now my playground is giving me this error: "Could not connect to websocket endpoint ws://192.168.150.98:3000/api/graphql. Please check if the endpoint url is correct."
TypeDefs:
type Subscription {
postAdded: Post
}
type Post {
author: String
comment: String
}
type Query {
posts: [Post]
}
type Mutation {
addPost(author: String, comment: String): Post
}
Resolvers:
Query: {
posts(root, args, context) {
return Posts;
}
}
Mutation: {
addPost(root, args, context) {
pubsub.publish(POST_ADDED, { postAdded: args });
return Posts.add(args);
}
},
Subscription: {
postAdded: {
// Additional event labels can be passed to asyncIterator creation
subscribe: () => pubsub.asyncIterator([POST_ADDED]),
},
}
First question here, thank u in advance! :)
it can also be a little easier
1.
yarn add apollo-server-express
or
npm install apollo-server-express
create file ./server/index.js
import { ApolloServer, gql } from 'apollo-server-express'
// Construct a schema, using GraphQL schema language
const typeDefs = gql`
type Query {
hello: String
}
`
// Provide resolver functions for your schema fields
const resolvers = {
Query: {
hello: () => 'Hello world!',
},
}
const server = new ApolloServer({ typeDefs, resolvers })
export default server
add in your nuxt.config.js
import server from './server'
export default {
// ... your nuxt config stuff
// ...
hooks: {
render: {
async before({
nuxt: {
server: { app },
},
}) {
await server.applyMiddleware({ app, path: '/api' })
console.log(`π ApolloServer ready at /api`)
},
},
}
}
I found a hacky way to achieve it, import the code as a nuxt module:
import http from 'http'
export default function () {
this.nuxt.hook('render:before', async () => {
const server = require("./apollo")()
// apply Apollo to Express
server.applyMiddleware({ app: this.nuxt.renderer.app });
console.log(`π ApolloServer ready at ${server.graphqlPath}`);
const httpServer = http.createServer(this.nuxt.renderer.app);
// apply SubscriptionHandlers to httpServer
server.installSubscriptionHandlers(httpServer);
console.log(`π ApolloSubscriptions ready at ${server.subscriptionsPath}`);
// overwrite nuxt.server.listen()
this.nuxt.server.listen = (port, host) => new Promise(resolve => httpServer.listen(port || 3000, host || 'localhost', resolve))
// close this httpServer on 'close' event
this.nuxt.hook('close', () => new Promise(httpServer.close))
})
}
Tho I'm now using a probably more stable way, using nuxt programmatically!
With hapi instead of express, since express is giving me trouble compiling and not showing the loading-screen(progress of building).
Just use npx create-nuxt-app and create an app with a hapi server backend.
The code with hapi would look like this:
const consola = require('consola')
const Hapi = require('#hapi/hapi')
const HapiNuxt = require('#nuxtjs/hapi')
async function start () {
const server = require('./apollo/index')()
const app = new Hapi.Server({
host: process.env.HOST || '127.0.0.1',
port: process.env.PORT || 3000
})
await app.register({
plugin: HapiNuxt
})
app.route(await require('./routes')())
await server.applyMiddleware({
app,
path: '/graphql'
});
console.log(`π ApolloServer ready at ${server.graphqlPath}`);
await server.installSubscriptionHandlers(app.listener)
console.log(`π ApolloSubscriptions ready at ${server.subscriptionsPath}`);
await app.start()
consola.ready({
message: `Server running at: ${app.info.uri}`,
badge: true
})
}
process.on('unhandledRejection', error => consola.error(error))
start().catch(error => console.log(error))
Maybe i can help somebody
An easier way is to use the getMiddleware() method of Apollo Server Express:
Create a file under ./api/index.js:
const { ApolloServer, gql } = require('apollo-server-express')
const express = require('express')
const typeDefs = gql`
type Query {
hello: String
}
`
const resolvers = {
Query: {
hello: () => 'Hello world!',
},
}
const server = new ApolloServer({ typeDefs, resolvers })
const app = express()
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(server.getMiddleware())
module.exports = app
and then register it in ./nuxt.config.js:
{
// other nuxt config ...
serverMiddleware: [{ path: '/api', handler: '~/api/index.js' }],
}
I have developed a react application using next.js.
Now I want to deploy it to Google Cloud App Engine.
The application does include the react frontend and a mock-API (including mock.db) in order to store data temporararily while in development.
The issue is the following:
The first instance I opened did work correctly. As soon as I opened it in another browser only the react app was served but the API was not there (resulting in the React app only showing frames of controls and no data). The API server is accessible through localhost:3033
The same persits for my colleage who tried to open it, only seeing whiteness.
I have not configured anything extra on Google Cloud App Engine, just vanilla basically.
Does this have something todo with App Engine spinning up extra instances ? I cant figure out what could cause this issue.
package.json
"prestart:api": "node createMockDb.js",
"start:api": "node apiServer.js",
"dev": "node server.js",
"build": "next build",
"start": "cross-env NODE_ENV=production node server.js & node createMockDB.js & node apiServer.js"
server.js
const express = require("express");
const next = require("next");
const port = parseInt(process.env.PORT, 10) || 8080;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.get("/products/overview", (req, res) => {
return app.render(req, res, "/products/overview", req.query);
});
server.get("/products/roadmap", (req, res) => {
return app.render(req, res, "/products/roadmap", req.query);
});
server.get("/strategy/goals", (req, res) => {
return app.render(req, res, "/strategy/goals", req.query);
});
server.get("/strategy/metrics", (req, res) => {
return app.render(req, res, "/strategy/metrics", req.query);
});
/* server.get("/posts/:id", (req, res) => {
return app.render(req, res, "/posts", { id: req.params.id });
}); */
server.all("*", (req, res) => {
return handle(req, res);
});
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
apiServer.js
/* eslint-disable func-names */
/* eslint-disable no-console */
const jsonServer = require("json-server");
const server = jsonServer.create();
const path = require("path");
const router = jsonServer.router(path.join(__dirname, "server/db.json"));
const middlewares = jsonServer.defaults({
static: "node_modules/json-server/dist"
});
server.use(middlewares);
server.use(jsonServer.bodyParser);
server.use(function(req, res, next) {
setTimeout(next, 0);
});
function createSlug(value) {
return value
.replace(/[^a-z0-9_]+/gi, "-")
.replace(/^-|-$/g, "")
.toLowerCase();
}
function validateProduct(product) {
if (!product.title) return "Title is required.";
if (!product.tagline) return "Tagline is required.";
if (!product.description) return "Description is required.";
return "";
}
server.use((req, res, next) => {
if (req.method === "POST") {
req.body.createdAt = Date.now();
}
next();
});
server.post("/products/", function(req, res, next) {
const error = validateProduct(req.body);
if (error) {
res.status(400).send(error);
} else {
req.body.slug = createSlug(req.body.title);
next();
}
});
server.use(router);
const port = 3033;
server.listen(port, () => {
console.log(`JSON Server is running on port ${port}`);
});
You appear to be attempting to start multiple web servers from your npm start command in a single app engine instance:
"start": "cross-env NODE_ENV=production node server.js & node createMockDB.js & node apiServer.js"
I've never seen this before and I doubt very much GAE can deal with it. GAE expects a single node application serving requests on port process.env.PORT.
If you want multiple different servers running within the same GAE project, you should probably deploy them as independently as different services. Each of them should have an app.yaml that specifies a unique service name, and you'll deploy them each independently. The documentation here is fairly comprehensive.