Code Monkey home page Code Monkey logo

netlify-express's Introduction

Express.js on Netlify Example

Netlify Status

Deploy to Netlify

An example of how to host an Express.js app on Netlify using serverless-http. See express/server.js for details, or check it out at https://netlify-express.netlify.com/!

index.html simply loads html from the Express.js app using <object>, and the app is hosted at /.netlify/functions/server. Examples of how to access the Express.js endpoints:

curl https://netlify-express.netlify.com/.netlify/functions/server
curl https://netlify-express.netlify.com/.netlify/functions/server/another
curl --header "Content-Type: application/json" --request POST --data '{"json":"POST"}' https://netlify-express.netlify.com/.netlify/functions/server

netlify-express's People

Contributors

neverendingqs avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

netlify-express's Issues

WARNING in ./node_modules/express/lib/view.js

When yarn build:

WARNING in ./node_modules/express/lib/view.js
81:13-25 Critical dependency: the request of a dependency is an expression
 @ ./node_modules/express/lib/view.js
 @ ./node_modules/express/lib/application.js
 @ ./node_modules/express/lib/express.js
 @ ./node_modules/express/index.js
 @ ./express/server.js

Doesn't work with res.sendFile() and templates

This workaround with <object> doesn't work in production neither with res.sendFile() nor with templates:

router.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, './index.html'));
});
router.get('/', (req, res) => {
  res.render('index', {
      title: 'Hello, World!',
      message: 'Works!'
  });
});

Here is an error:

error

Trying to connect to sql database got an error

link to gihub repo https://github.com/riteshkarwa/my-repository

created a connect.js file the code live in there

var connection = mysql.createConnection({
          host : "remotemysql.com",
          user: "",
          database: "",
          password: ""
          //port:"3306"
        });
    }

exports.handler = function (event, context, callback) {
    context.callbackWaitsForEmptyEventLoop =false;
    connection.connect(function(err) {
      if (err) {
        console.error('Error connecting: ' + err.stack);
      }
      console.log('Connected as thread id: ' + connection.threadId);
    });

var results=[];
//SQL Query > Select Data

return new Promise((resolve, reject) => {
  const readTable = `SELECT * FROM num_of_likes`;
  connection.query(readTable, (err, results, fields) => {
    if (err) {
     reject(err);
    } else {
      resolve({statusCode: 200, body: {results}});
    }
  });
});

*Lambda server is listening on 9000
Request from ::1: GET /connect
Error connecting: Error: Received packet in the wrong sequence.
at A._parsePacket (/Users/riteshkarwa/netlify/functions/connect.js:1:93387)
at A._parsePacket (/Users/riteshkarwa/netlify/functions/connect.js:1:102113)
at A.write (/Users/riteshkarwa/netlify/functions/connect.js:1:96341)
at A.write (/Users/riteshkarwa/netlify/functions/connect.js:1:89855)
at Socket. (/Users/riteshkarwa/netlify/functions/connect.js:1:7771)
at Socket. (/Users/riteshkarwa/netlify/functions/connect.js:1:6835)
at Socket.emit (events.js:210:5)
at addChunk (_stream_readable.js:309:12)
at readableAddChunk (_stream_readable.js:290:11)
at Socket.Readable.push (_stream_readable.js:224:10)
at TCP.onStreamRead (internal/stream_base_commons.js:182:23)

at A._enqueue (/Users/riteshkarwa/netlify/functions/connect.js:1:91233)
at A.handshake (/Users/riteshkarwa/netlify/functions/connect.js:1:89978)
at o.connect (/Users/riteshkarwa/netlify/functions/connect.js:1:8643)
at Object.E.handler (/Users/riteshkarwa/netlify/functions/connect.js:1:238235)
at /Users/riteshkarwa/netlify/node_modules/netlify-lambda/lib/serve.js:144:27
at Layer.handle [as handle_request] (/Users/riteshkarwa/netlify/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/riteshkarwa/netlify/node_modules/express/lib/router/route.js:137:13)
at next (/Users/riteshkarwa/netlify/node_modules/express/lib/router/route.js:131:14)
at next (/Users/riteshkarwa/netlify/node_modules/express/lib/router/route.js:131:14)
at next (/Users/riteshkarwa/netlify/node_modules/express/lib/router/route.js:131:14)
at next (/Users/riteshkarwa/netlify/node_modules/express/lib/router/route.js:131:14)
at next (/Users/riteshkarwa/netlify/node_modules/express/lib/router/route.js:131:14)
at next (/Users/riteshkarwa/netlify/node_modules/express/lib/router/route.js:131:14)
at Route.dispatch (/Users/riteshkarwa/netlify/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/riteshkarwa/netlify/node_modules/express/lib/router/layer.js:95:5)
at /Users/riteshkarwa/netlify/node_modules/express/lib/router/index.js:281:22
Connected as thread id: 15223054
Response with status 500 in 2105 ms.
Error during invocation: Error: Received packet in the wrong sequence.
at A._parsePacket (/Users/riteshkarwa/netlify/functions/connect.js:1:93387)
at A._parsePacket (/Users/riteshkarwa/netlify/functions/connect.js:1:102113)
at A.write (/Users/riteshkarwa/netlify/functions/connect.js:1:96341)
at A.write (/Users/riteshkarwa/netlify/functions/connect.js:1:89855)
at Socket. (/Users/riteshkarwa/netlify/functions/connect.js:1:7771)
at Socket. (/Users/riteshkarwa/netlify/functions/connect.js:1:6835)
at Socket.emit (events.js:210:5)
at addChunk (_stream_readable.js:309:12)
at readableAddChunk (_stream_readable.js:290:11)
at Socket.Readable.push (_stream_readable.js:224:10)
at TCP.onStreamRead (internal/stream_base_commons.js:182:23)

at A._enqueue (/Users/riteshkarwa/netlify/functions/connect.js:1:91233)
at A.handshake (/Users/riteshkarwa/netlify/functions/connect.js:1:89978)
at o.connect (/Users/riteshkarwa/netlify/functions/connect.js:1:8643)
at Object.E.handler (/Users/riteshkarwa/netlify/functions/connect.js:1:238235)
at /Users/riteshkarwa/netlify/node_modules/netlify-lambda/lib/serve.js:144:27
at Layer.handle [as handle_request] (/Users/riteshkarwa/netlify/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/riteshkarwa/netlify/node_modules/express/lib/router/route.js:137:13)
at next (/Users/riteshkarwa/netlify/node_modules/express/lib/router/route.js:131:14)
at next (/Users/riteshkarwa/netlify/node_modules/express/lib/router/route.js:131:14)
at next (/Users/riteshkarwa/netlify/node_modules/express/lib/router/route.js:131:14)
at next (/Users/riteshkarwa/netlify/node_modules/express/lib/router/route.js:131:14)
at next (/Users/riteshkarwa/netlify/node_modules/express/lib/router/route.js:131:14)
at next (/Users/riteshkarwa/netlify/node_modules/express/lib/router/route.js:131:14)
at Route.dispatch (/Users/riteshkarwa/netlify/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/riteshkarwa/netlify/node_modules/express/lib/router/layer.js:95:5)
at /Users/riteshkarwa/netlify/node_modules/express/lib/router/index.js:281:22 {
code: ‘PROTOCOL_INCORRECT_PACKET_SEQUENCE’,
fatal: true

TypeScript Example

Hi there,

I'm trying to use your fine docs to run Express as a serverless function on Netlify, but my function file is written in TypeScript, which is necessary for my use case.

I've tried:

const handler = serverless(app);
export { handler };

Unfortunately, this results in a 404 when I try to do a get on a route when the function is being served by netlify functions:serve, using the Netlify CLI.

Am I missing a step here? Did I do the export wrong? A TypeScript example would be very useful here.

Thanks!

How to view console.log()'s?

Hello,

I have an app running using this architecture, but I can't figure out where to find any of the logs that I'm making to my console inside my server.

... Anyone?

Can not run it locally

This were the only changes I've done

diff
And these is the message error I get:

You have requested the root of http://localhost:9000. This is likely a mistake. netlify-lambda serves functions at http://localhost:9000/.netlify/functions/your-function-name; please fix your code.

I tried to debug the middlewares involved but could not make any conclusion, neither now how to fix it.

This is a router path success:
success-router

This is an app path failure:
app-error

It seems like paths for the router works, but not for the app.
Maybe there is something I am missing to run it locally?

Thanks in advanced

Details about /.netlify Folder

Hey, how you are you?
I hope you are doing great during this quarantine like me =)

So, I'm trying to implement this solution in my repo, a simple repo that runs in express and I'm developing some edits to my index.js file according this post: https://www.netlify.com/blog/2018/09/13/how-to-run-express.js-apps-with-netlify-functions/#trying-it-out and you repo:

I'm facing some issue to get info about the .netlify folder that you write inside express/server.js

Here's my code highlighted with your approach:

require('dotenv').config()
const ACCESS_TOKEN = process.env.CLIENT_ACCESS_TOKEN;
const APIAI_SESSION_ID = process.env.DEV_ACCESS_TOKEN;


const express = require('express');
const app = express();
const path = require('path');
const serverless = require('serverless-http');
const bodyParser = require('body-parser');
const router = express.Router();


app.use(express.static(__dirname + '/views')); // html
app.use(express.static(__dirname + '/public')); // js, css, images

//HERE IS MY ISSUE
app.use('/.netlify/functions/server', router);  // path must route to lambda


const server = app.listen(process.env.PORT || 5000, () => {
  console.log('Express server listening on port %d in %s mode', server.address().port, app.settings.env);
});


const apiai = require('apiai')(ACCESS_TOKEN);

//WEB UI
app.get('/', (req, res) => {
  res.sendFile('index.html');
});

const io = require('socket.io')(server);

io.on('connection', function (socket) {
  socket.on('chat message', (text) => {

    // Get a reply from API.AI

    let apiaiReq = apiai.textRequest(text, {
      sessionId: APIAI_SESSION_ID
    });

    apiaiReq.on('response', (response) => {
      let aiText = response.result.fulfillment.speech;
      socket.emit('bot reply', aiText); // Send the result back to the browser!
    });

    apiaiReq.on('error', (error) => {
      console.log(error);
    });

    apiaiReq.end();

  });
});


module.exports = app;
module.exports.handler = serverless(app);

Glad if you could give me some guidance, thanks!

Netlify-lambda deprecated

Is this repo still valid for a good example of the edge-functions setup?
I've seen the docs saying that netlify-lambed is now deprecated and the last commit in this repo is 4y old, but the docs still point here.

Is this compatible with Gatsby somehow?

Hi There, have you got any advice how to get this working from within Gatsby? I suspect the issue is coming from routing...

It works locally, but I get Cannot GET /.netlify/functions/server/ when visiting the location.

Only root route is working locally

I got the following code

router.get('/', (req, res) => {
  res.status(200).send("/")
});

router.get('/another', (req, res) => res.json({
  route: req.originalUrl
}));

app.use(bodyParser.json());
app.use('/.netlify/functions/server', router); // path must route to lambda
app.use('/', (req, res) => res.sendFile(path.join(__dirname, '../index.html')));

module.exports = app;
module.exports.handler = serverless(app);

Locally it will always just return the / path og never /another

Any ideas why? :)

Only root route returns

https://netlify-express.netlify.com/ renders,
https://netlify-express.netlify.com/another returns a 404.

I've been trying to build a simple app using this as a boilerplate, and none of my defined routes work apart from /. Any ideas?

Function invocation failed: TypeError: require is not a function error

I'm building a web app with Vue, which will use Netlify Lambda functions and Express.js as the server-side. I have followed this repo's structure almost exactly, and I'm following the "How to run Express.js with Netlify functions" guide as well. I am also using the Netlify Lambda plugin for Vue CLI to integrate the lambda functions into my Vue build process.

I have a small lambda function called server.js. When this function is called, it will grab data from the Spotify API.

'use strict'; 

const serverless = require("serverless-http");
const SpotifyWebApi = require("spotify-web-api-node");
const express = require("express");
const app = express();
const bodyParser = require("body-parser");

const router = express.Router();

router.get("/search", (req, res) => {
    // function that searches for a song with the Spotify API
});

app.use(bodyParser.json());
app.use('/.netlify/functions/server', router);  // path must route to lambda

module.exports = app;
module.exports.handler = serverless(app);

This should work - it follows the pattern in the server.js file in this repo. I create an Express app, add a GET endpoint called search to the Express API, and then export the Express app as the handler for the Netlify Lambda functions.

However, I keep getting this cryptic, vague error whenever I navigate to the url for the Lambda function: TypeError: a is not a function. I have researched this error and tried a bunch of the hotfixes and workarounds, but they haven't fixed the issue. Here is the full stack trace:

{"errorMessage":"a is not a function","errorType":"TypeError","stackTrace":["i (/var/task/server.js:1:220)","Object.<anonymous> (/var/task/server.js:314:35760)","i (/var/task/server.js:1:220)","Object.e.exports.a.debug (/var/task/server.js:159:7043)","i (/var/task/server.js:1:220)","Object.<anonymous> (/var/task/server.js:159:5636)","i (/var/task/server.js:1:220)","Object.<anonymous> (/var/task/server.js:314:13004)","i (/var/task/server.js:1:220)"]}

If I run the server locally, I get this error instead:

Function invocation failed: TypeError: require is not a function

If this question does not have enough detail or you want to look at my config files or my exact function, feel free to explore the Github repo for my small web app: https://github.com/vintners/music-calc-app

Also, this is the URL for the server.js Lambda function on my Netlify site: https://happy-goodall-8bd7c9.netlify.com/.netlify/functions/server

Is my Lambda function set up incorrectly?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.