Introduction to express use of nodejs

Express Framework

Come from JavaScript Standard Reference Tutorial (alpha) by Ruan Yifen

Catalog

Summary

Express is currently the most popular Node.js-based Web development framework, allowing you to quickly build a fully functional website.

Express is easy to get started by creating a new project directory, presumably called hello-world.

$ mkdir hello-world

Enter the directory and create a new package.json file, which reads as follows.

{
  "name": "hello-world",
  "description": "hello world test app",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "express": "4.x"
  }
}

The code above defines the name, description, version, and so on of the project, and specifies Express that requires a version greater than 4.0.

Then you can install it.

$ npm install

After executing the above command, a new startup file is created in the project root directory, assuming it is called index.js.

var express = require('express');
var app = express();

app.use(express.static(__dirname + '/public'));

app.listen(8080);

Then, run the startup script above.

$ node index

You can now access http://localhost:8080, which opens the public subdirectory of the current directory in your browser (strictly, the index.html file of the public directory).If there is a picture file, my_image.png, in the public directory, you can access it at http://localhost:8080/my_image.png.

You can also generate dynamic web pages in index.js.

// index.js

var express = require('express');
var app = express();
app.get('/', function (req, res) {
  res.send('Hello world!');
});
app.listen(3000);

Then, run the startup script from the command line to access the project site in the browser.

$ node index

The above code launches a website on port 3000 of this machine and the web page shows Hello World.

Launch the app.get method of the script index.js to specify the callback functions corresponding to different access paths, called routing.The code above specifies only the callback function of the root directory, so there is only one route record.In practical applications, there may be multiple routing records.

// index.js

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello world!');
});
app.get('/customer', function(req, res){
  res.send('customer page');
});
app.get('/admin', function(req, res){
  res.send('admin page');
});

app.listen(3000);

At this point, it is best to put the route in a separate file, such as creating a new routes subdirectory.

// routes/index.js

module.exports = function (app) {
  app.get('/', function (req, res) {
    res.send('Hello world');
  });
  app.get('/customer', function(req, res){
    res.send('customer page');
  });
  app.get('/admin', function(req, res){
    res.send('admin page');
  });
};

Then, the original index.js becomes the following.

// index.js
var express = require('express');
var app = express();
var routes = require('./routes')(app);
app.listen(3000);

Operating principle

Bottom level: http module

The Express framework is built on the node.js built-in http module.The HTTP module generates the original code for the server as follows.

var http = require("http");

var app = http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello world!");
});

app.listen(3000, "localhost");

The key to the above code is the HTTP module's createServer method, which means to generate an HTTP server instance.This method accepts a callback function whose parameters are request and response objects representing HTTP requests and HTTP responses, respectively.

The core of the Express framework is the repackaging of http modules.The code above is rewritten in Express as follows.

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello world!');
});

app.listen(3000);

Compare the two pieces of code and you can see that they are very close.Instead of creating a new app instance using the http.createServer method, an Epress instance is generated using the Express construction method.Both callback functions are the same.The Express framework is equivalent to an HTTP module with an intermediate layer added.

What is Middleware

In short, middleware is a function that handles HTTP requests.Its main feature is that one middleware is processed and passed to the next.App instances invoke a series of middleware while running.

Each middleware can receive three parameters from an App instance, one for the request object (representing the HTTP request), one for the response object (representing the HTTP response), and the next callback function (representing the next middleware).Each middleware can process HTTP requests (request objects) and decide whether to call the next method to pass the request object to the next middleware.

A middleware that does nothing but passes the request object is shown below.

function uselessMiddleware(req, res, next) {
  next();
}

Next of the above code is the next middleware.If it has parameters, it means an error is thrown, which is the wrong text.

function uselessMiddleware(req, res, next) {
  next('Error!');
}

After an error is thrown, subsequent middleware will not execute until an error-handling function is found.

use method

use is the method by which express ion registers the middleware and returns a function.Below is an example of calling two Middleware in succession.

var express = require("express");
var http = require("http");

var app = express();

app.use(function(request, response, next) {
  console.log("In comes a " + request.method + " to " + request.url);
  next();
});

app.use(function(request, response) {
  response.writeHead(200, { "Content-Type": "text/plain" });
  response.end("Hello world!\n");
});

http.createServer(app).listen(1337);

The code above uses the app.use method to register two middleware.When an HTTP request is received, the first middleware is called, a line of information is output in the console, and the execution right is passed to the second middleware through the next method, which outputs the HTTP response.Since the second middleware does not call the next method, the request object is no longer passed back.

The use r method can judge the access path internally, so that a simple route can be achieved by returning different web page contents according to different request web addresses.

var express = require("express");
var http = require("http");

var app = express();

app.use(function(request, response, next) {
  if (request.url == "/") {
    response.writeHead(200, { "Content-Type": "text/plain" });
    response.end("Welcome to the homepage!\n");
  } else {
    next();
  }
});

app.use(function(request, response, next) {
  if (request.url == "/about") {
    response.writeHead(200, { "Content-Type": "text/plain" });
  } else {
    next();
  }
});

app.use(function(request, response) {
  response.writeHead(404, { "Content-Type": "text/plain" });
  response.end("404 error!\n");
});

http.createServer(app).listen(1337);

The code above uses the request.url attribute to determine the requested address and return different content.Note that the app.use method registers a total of three middleware, and as long as the request path matches, execution will not be given to the next middleware.Therefore, the last middleware returns a 404 error, that is, the previous middleware does not match the request path and cannot find the requested resource.

In addition to determining the requested web address within the callback function, the use method also allows the request web address to be written in the first parameter.This means that the subsequent middleware will not take effect until the request path matches this parameter.Undoubtedly, this makes writing clearer and more convenient.

app.use('/path', someMiddleware);

The code above indicates that only a request to the root directory calls a middleware.

Therefore, the code above can be written as follows.

var express = require("express");
var http = require("http");

var app = express();

app.use("/home", function(request, response, next) {
  response.writeHead(200, { "Content-Type": "text/plain" });
  response.end("Welcome to the homepage!\n");
});

app.use("/about", function(request, response, next) {
  response.writeHead(200, { "Content-Type": "text/plain" });
  response.end("Welcome to the about page!\n");
});

app.use(function(request, response) {
  response.writeHead(404, { "Content-Type": "text/plain" });
  response.end("404 error!\n");
});

http.createServer(app).listen(1337);

Express method

all method and HTTP verb method

Express provides some aliases for the use method for different requests.For example, the code above can also be written as an alias.

var express = require("express");
var http = require("http");
var app = express();

app.all("*", function(request, response, next) {
  response.writeHead(200, { "Content-Type": "text/plain" });
  next();
});

app.get("/", function(request, response) {
  response.end("Welcome to the homepage!");
});

app.get("/about", function(request, response) {
  response.end("Welcome to the about page!");
});

app.get("*", function(request, response) {
  response.end("404!");
});

http.createServer(app).listen(1337);

The all method in the code above indicates that all requests must pass through the middleware, and the'*'in the parameter indicates that all paths are valid.The get method is that only a GET verb's HTTP request passes through the middleware, and its first parameter is the path of the request.Since the callback function of the get method does not call the next method, as long as one of the middleware is called, the subsequent middleware will no longer be called.

In addition to the get method, Express also provides post, put, delete methods, where HTTP verbs are Express methods.

The first parameter of these methods is the requested path.Express allows pattern matching in addition to absolute matching.

app.get("/hello/:who", function(req, res) {
  res.end("Hello, " + req.params.who + ".");
});

The above code will match the'/hello/alice'web address, where Alice will be captured as the value of the req.params.who attribute.It is important to note that after capture, the address needs to be checked and unsafe characters filtered. The above writing is for demonstration purposes only. User-provided values should not be used directly in production.

If a question mark is added after the mode parameter, it means that the parameter is optional.

app.get('/hello/:who?',function(req,res) {
	if(req.params.id) {
    	res.end("Hello, " + req.params.who + ".");
	}
    else {
    	res.send("Hello, Guest.");
	}
});

Below are some examples of more complex pattern matching.

app.get('/forum/:fid/thread/:tid', middleware)

// Match/commits/71dbb9c
// Or git-formatted addresses such as / commits/71dbb9c..4c084f9
app.get(/^\/commits\/(\w+)(?:\.\.(\w+))?$/, function(req, res){
  var from = req.params[0];
  var to = req.params[1] || 'HEAD';
  res.send('commit range ' + from + '..' + to);
});

set method

The set method is used to specify the value of a variable.

app.set("views", __dirname + "/views");

app.set("view engine", "jade");

The code above uses the set method to specify values for system variables "views" and "view engine".

response object

(1) response.redirect method

The response.redirect method allows redirection of web addresses.

response.redirect("/hello/anime");
response.redirect("http://www.example.com");
response.redirect(301, "http://www.example.com"); 

(2) response.sendFile method

The response.sendFile method is used to send files.

response.sendFile("/path/to/anime.mp4");

(3) response.render method

The response.render method is used to render web page templates.

app.get("/", function(request, response) {
  response.render("index", { message: "Hello World" });
});

The code above uses the render method to pass the message variable into the index template and render it as an HTML page.

requst object

(1)request.ip

The request.ip property is used to obtain the IP address of an HTTP request.

(2)request.files

request.files is used to get the uploaded file.

Set up HTTPs server

Setting up an HTTPs encryption server using Express is also simple.

var fs = require('fs');
var options = {
  key: fs.readFileSync('E:/ssl/myserver.key'),
  cert: fs.readFileSync('E:/ssl/myserver.crt'),
  passphrase: '1234'
};

var https = require('https');
var express = require('express');
var app = express();

app.get('/', function(req, res){
  res.send('Hello World Expressjs');
});

var server = https.createServer(options, app);
server.listen(8084);
console.log('Server is running on port 8084');

Project Development Instances

Write startup scripts

The previous section used the express command to create the project automatically, or you can create all the new files manually without using this command.

Start by creating a project directory (assuming it is called demo).Enter the directory, create a new package.json file, and write the project's configuration information.

{
   "name": "demo",
   "description": "My First Express App",
   "version": "0.0.1",
   "dependencies": {
      "express": "3.x"
   }
}

In the project directory, create a new file, app.js.The code for the project is in this file.

var express = require('express');
var app = express();

The code above first loads the express module and assigns it to the variable express.Then, an expression instance is generated and assigned to the variable app.

Next, set the parameters for the express instance.

// Set the port variable, meaning access port
app.set('port', process.env.PORT || 3000);

// Set the views variable, which means the directory where the view is stored
app.set('views', path.join(__dirname, 'views'));

// Set the view engine variable, which means Web Template Engine
app.set('view engine', 'jade');

app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);

// Set static file directories, such as local files
// Directory is demo/public/images, access
// The web address is displayed at http://localhost:3000/images
app.use(express.static(path.join(__dirname, 'public')));

The set method in the code above is used to set internal variables, and the use method is used to call the express middleware.

Finally, call the instance method listen and have it listen on a predefined port (3000).

app.listen(app.get('port'));

At this time, you can access http://127.0.0.1:3000 in your browser by running the following command.

node app.js

A Web page prompt "Cannot GET /" indicates that no content is specified for the root path of the Web site to display.So the next step is to configure the route.

Configure Routing

Routing refers to specifying different processing methods for different access paths.

(1) Specify the root path

In app.js, specify the root path's processing method first.

app.get('/', function(req, res) {
   res.send('Hello World');
});

The get method of the code above represents the processing of GET requests from clients.Correspondingly, there are app.post, app.put, app.del (delete is a JavaScript reserved word, so it is called del) methods.

The first parameter of the get method is the access path, and the forward slash (/) represents the root path; the second parameter is the callback function, whose req parameter represents the HTTP request sent by the client, and the res parameter represents the HTTP response sent to the client, both of which are objects.Inside the callback function, the send method of the HTTP response is used to indicate that a string is sent to the browser.Then, run the following command.

node app.js

At this point, when you visit http://127.0.0.1:3000 in your browser, the web page will display "Hello World".

If you need to specify HTTP header information, the callback function must be written in a different way, using the setHeader and end methods.

app.get('/', function(req, res){
  var body = 'Hello World';
  res.setHeader('Content-Type', 'text/plain');
  res.setHeader('Content-Length', body.length);
  res.end(body);
});

(2) Specify a specific path

The above is the case with the root directory, and the following is another example.Assuming the user accesses/api path, you want to return a JSON string.At this point, the get can write like this.

app.get('/api', function(request, response) {
   response.send({name:"Zhang San",age:40});
});

The code above indicates that the send method can send objects directly in addition to sending strings.After restarting the node and accessing the path/api, the browser will display a JSON object.

{
  "name": "Zhang San",
  "age": 40
}

We can also encapsulate the callback functions of app.get into modules.Start by creating an api.js file under the routes directory.

// routes/api.js

exports.index = function (req, res){
  res.json(200, {name:"Zhang San",age:40});
}

Then, load the module in app.js.

// app.js

var api = require('./routes/api');
app.get('/api', api.index);

When you visit now, you will see the same results as your last visit.

This is sufficient if you want to send simple text messages to your browser, but if you want to send complex content to your browser, you should still use a web page template.

Static Web Page Template

Within the project directory, create a subdirectory views for storing web page templates.

Assume that this project has three paths: root (/), self-introduction (/about), and article (/article).Then, app.js can write as follows:

var express = require('express');
var app = express();
 
app.get('/', function(req, res) {
   res.sendfile('./views/index.html');
});
 
app.get('/about', function(req, res) {
   res.sendfile('./views/about.html');
});
 
app.get('/article', function(req, res) {
   res.sendfile('./views/article.html');
});
 
app.listen(3000);

The code above indicates that the three paths correspond to three templates in the views directory: index.html, about.html, and article.html.In addition, the method of sending information to the server has changed from send to sendfile, which is dedicated to sending files.

Assume the following for index.html:

<html>
<head>
   <title>home page</title>
</head>
 
<body>
<h1>Express Demo</h1>
 
<footer>
<p>
   <a href="/">home page</a> - <a href="/about">Introduce oneself to</a> - <a href="/article">Article</a>
</p>
</footer>
 
</body>
</html>

The code above is a static web page.If you want to present dynamic content, you must use dynamic web page templates.

Dynamic Web Page Template

The real beauty of a website is dynamic web pages. Let's see how to make a website with dynamic web pages.

Install Template Engine

Express supports multiple template engines, using the server-side version of the Handlebars template engine hbs Template Engine.

Install hbs first.

npm install hbs --save-dev

The code above installs the hbs module in the subdirectory node_modules of the project directory.The save-dev parameter indicates that the dependencies are written to the package.json file.After installation, the package.json file becomes the following:

// package.json file

{
  "name": "demo",
  "description": "My First Express App",
  "version": "0.0.1",
  "dependencies": {
    "express": "3.x"
  },
  "devDependencies": {
    "hbs": "~2.3.1"
  }
}

After installing the template engine, overwrite app.js.

// app.js file

var express = require('express');
var app = express();

// Load hbs module
var hbs = require('hbs');

// Specify the suffix name of the template file as html
app.set('view engine', 'html');

// Run hbs module
app.engine('html', hbs.__express);

app.get('/', function (req, res){
	res.render('index');
});

app.get('/about', function(req, res) {
	res.render('about');
});

app.get('/article', function(req, res) {
	res.render('article');
});

The code above uses the render method instead to render the page template.The parameter to the render method is the file name of the template, which is placed in the subdirectory views by default, and the suffix name has been previously specified as html, which can be omitted.So res.render('index') refers to handing over the index.html file under the subdirectory views to the template engine hbs for rendering.

New Data Script

Rendering refers to the process of substituting data into templates.In practice, data is stored in a database. To simplify the problem, it is assumed that the data is stored in a script file.

In the project directory, create a new file, blog.js, to store the data.Blog.js is written in accordance with the CommonJS specification so that it can be loaded by require statements.

// blog.js file

var entries = [
	{"id":1, "title":"First", "body":"text", "published":"6/2/2013"},
	{"id":2, "title":"Second Article", "body":"text", "published":"6/3/2013"},
	{"id":3, "title":"Article 3", "body":"text", "published":"6/4/2013"},
	{"id":4, "title":"Article 4", "body":"text", "published":"6/5/2013"},
	{"id":5, "title":"Article 5", "body":"text", "published":"6/10/2013"},
	{"id":6, "title":"Article 6", "body":"text", "published":"6/12/2013"}
];

exports.getBlogEntries = function (){
   return entries;
}
 
exports.getBlogEntry = function (id){
   for(var i=0; i < entries.length; i++){
      if(entries[i].id == id) return entries[i];
   }
}

New Page Template

Next, create a new template file, index.html.

<!-- views/index.html file -->

<h1>Article List</h1>
 
{{#each entries}}
   <p>
      <a href="/article/{{id}}">{{title}}</a><br/>
      Published: {{published}}
   </p>
{{/each}}

Template file about.html.

<! -- views/about.html file-->

<h1>Self-introduction</h1>
 
<p>Body</p>

Template file article.html.

<!-- views/article.html file -->

<h1>{{blog.title}}</h1>
Published: {{blog.published}}
 
<p/>
 
{{blog.body}}

As you can see, all three template files above have only the body of the page.Because the page layout is shared, the section of the layout can create a new file layout.html separately.

<!-- views/layout.html file -->

<html>
 
<head>
   <title>{{title}}</title>
</head>
 
<body>
 
	{{{body}}}
 
   <footer>
      <p>
         <a href="/">home page</a> - <a href="/about">Introduce oneself to</a>
      </p>
   </footer>
    
</body>
</html>

Rendering Template

Finally, overwrite the app.js file.

// app.js file

var express = require('express');
var app = express();
 
var hbs = require('hbs');

// Load Data Module
var blogEngine = require('./blog');
 
app.set('view engine', 'html');
app.engine('html', hbs.__express);
app.use(express.bodyParser());
 
app.get('/', function(req, res) {
   res.render('index',{title:"Recent Articles", entries:blogEngine.getBlogEntries()});
});
 
app.get('/about', function(req, res) {
   res.render('about', {title:"Introduce oneself to"});
});
 
app.get('/article/:id', function(req, res) {
   var entry = blogEngine.getBlogEntry(req.params.id);
   res.render('article',{title:entry.title, blog:entry});
});
 
app.listen(3000);

The render method in the code above now adds a second parameter representing the data bound by the template variable.

Now restart the node server and access http://127.0.0.1:3000.

node app.js

As you can see, the template has been successfully rendered with the loaded data.

Specify static file directory

Template files are stored in the views subdirectory by default.In this case, if you want to load static files (such as stylesheets, pictures, etc.) into a Web page, you need to specify a different directory to store the static files.

app.use(express.static('public'));

The code above is in the file app.js, specifying that the directory where static files are stored is public.Thus, when the browser makes a request for a non-HTML file, the server looks for the file in the public directory.For example, a browser makes a stylesheet request as follows:

<link href="/bootstrap/css/bootstrap.css" rel="stylesheet">

On the server side, look for the bootstrap.css file in the public/bootstrap/css/directory.

Express.Router Usage

Beginning with Express 4.0, the router functionality has become a separate component, Express.Router.Like a small express application, it has its own use, get, param, and route methods.

Basic Usage

First, Express.Router is a constructor that returns a router instance after being called.Then, use the HTTP verb method of the instance to specify callback functions for different access paths; finally, mount to a path.

var router = express.Router();

router.get('/', function(req, res) {
  res.send('home page');
});

router.get('/about', function(req, res) {
  res.send('about');
});

app.use('/', router);

The code above defines two access paths and mounts them to the root directory.If the last line is changed to app.use('/app', router), it is equivalent to two paths, /app and/app/about, with callback functions specified.

This practice of free mounting of routers provides greater flexibility for programs to define multiple router instances or mount the same router instance onto multiple routes.

router.route method

The route method of the router instance object, which accepts an access path as a parameter.

var router = express.Router();

router.route('/api')
	.post(function(req, res) {
		// ...
	})
	.get(function(req, res) {
		Bear.find(function(err, bears) {
			if (err) res.send(err);
			res.json(bears);
		});
	});

app.use('/', router);

router Middleware

The use method specifies the middleware for the router object, which processes the data before it is formally sent to the user.Here is an example of a middleware.

router.use(function(req, res, next) {
	console.log(req.method, req.url);
	next();	
});

In the code above, the next parameter of the callback function indicates that it accepts calls from other middleware.The next() in the body of the function indicates that the data is passed to the next middleware.

Note that the order in which the middleware is placed is important and equivalent to the order in which it is executed.Furthermore, the middleware must precede the HTTP verb method or it will not execute.

Processing of path parameters

The param method of the router object is used to process the path parameters and can be

router.param('name', function(req, res, next, name) {
	// Verify or otherwise process name...
	console.log(name);
	req.name = name;
	next();	
});

router.get('/hello/:name', function(req, res) {
	res.send('hello ' + req.name + '!');
});

In the code above, the get method specifies the name parameter for the access path, while the param method handles the name parameter.Note that the param method must precede the HTTP verb method.

app.route

Assuming app is an instance object of Express, Express 4.0 provides a route attribute for that object.app.route is actually an abbreviation of express.Router(), except for mounting directly to the root path.Therefore, callback functions that specify the get and post methods for the same path can be written as chains.

app.route('/login')
	.get(function(req, res) {
		res.send('this is the login form');
	})
	.post(function(req, res) {
		console.log('processing');
		res.send('processing the login form!');
	});

This writing of the code above is obviously very simple and clear.

Upload Files

First, insert a form for uploading files into the web page.

<form action="/pictures/upload" method="POST" enctype="multipart/form-data">
  Select an image to upload:
  <input type="file" name="image">
  <input type="submit" value="Upload Image">
</form>

The server script then establishes a route to the / upload directory.You can install the multer module, which provides many functions for uploading files.

var express = require('express');
var router = express.Router();
var multer = require('multer');

var uploading = multer({
  dest: __dirname + '../public/uploads/',
  // Set a limit to upload up to 1 file at a time, no larger than 1MB
  limits: {fileSize: 1000000, files:1},
})

router.post('/upload', uploading, function(req, res) {

})

module.exports = router

The above code uploads files to a local directory.Below is an example uploaded to Amazon S3.

First, add a CORS profile on top of S3.

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
  <CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
  </CORSRule>
</CORSConfiguration>

The above configuration allows any computer to send HTTP requests to your bucket.

Then, install aws-sdk.

$ npm install aws-sdk --save

Here is the server script.

var express = require('express');
var router = express.Router();
var aws = require('aws-sdk');

router.get('/', function(req, res) {
  res.render('index')
})

var AWS_ACCESS_KEY = 'your_AWS_access_key'
var AWS_SECRET_KEY = 'your_AWS_secret_key'
var S3_BUCKET = 'images_upload'

router.get('/sign', function(req, res) {
  aws.config.update({accessKeyId: AWS_ACCESS_KEY, secretAccessKey: AWS_SECRET_KEY});

  var s3 = new aws.S3()
  var options = {
    Bucket: S3_BUCKET,
    Key: req.query.file_name,
    Expires: 60,
    ContentType: req.query.file_type,
    ACL: 'public-read'
  }

  s3.getSignedUrl('putObject', options, function(err, data){
    if(err) return res.send('Error with S3')

    res.json({
      signed_request: data,
      url: 'https://s3.amazonaws.com/' + S3_BUCKET + '/' + req.query.file_name
    })
  })
})

module.exports = router

In the code above, the user accesses/sign path, logs in correctly, and receives a JSON object, which contains the data returned by S3 and a URL temporarily used to receive the uploaded file. The validity period is only 60 seconds.

The browser code is as follows.

// The HTML code is
// <br>Please select an image
// <input type="file" id="image">
// <br>
// <img id="preview">

document.getElementById("image").onchange = function() {
  var file = document.getElementById("image").files[0]
  if (!file) return

  sign_request(file, function(response) {
    upload(file, response.signed_request, response.url, function() {
      document.getElementById("preview").src = response.url
    })
  })
}

function sign_request(file, done) {
  var xhr = new XMLHttpRequest()
  xhr.open("GET", "/sign?file_name=" + file.name + "&file_type=" + file.type)

  xhr.onreadystatechange = function() {
    if(xhr.readyState === 4 && xhr.status === 200) {
      var response = JSON.parse(xhr.responseText)
      done(response)
    }
  }
  xhr.send()
}

function upload(file, signed_request, url, done) {
  var xhr = new XMLHttpRequest()
  xhr.open("PUT", signed_request)
  xhr.setRequestHeader('x-amz-acl', 'public-read')
  xhr.onload = function() {
    if (xhr.status === 200) {
      done()
    }
  }

  xhr.send(file)
}

The code above first listens for the file control's change event, and once it changes, requests a temporary upload URL from the server, then uploads the file to that URL.

Reference Links

 

Source: http://javascript.ruanyifeng.com/nodejs/express.html

Keywords: JSON AWS Javascript npm

Added by stickynote427 on Fri, 12 Jul 2019 20:35:19 +0300