欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

快速搭建一个简单的node服务器

程序员文章站 2022-05-08 23:51:01
...

需要安装的插件:

  • express
npm install express --save
  • body-parser (用来解析传递的参数)
npm install body-parser --save
  • cookie-parser(用来设置和获取cookie)
npm install cookie-parser --save

使用cookie-parser设置cookie,例如

var express = require("express");
var cookieParser = require("cookie-parser");
var app = express();
app.use(cookieParser());
app.get("/",function(req,res){
	res.cookie('username', 'Jack');
	//设置带有过期时间的cookie
	res.cookie(key,value,{expires:3600})
        res.send("你好");
});
 
app.listen(3000);


cookie-parser中,只是给req对象添加了cookies属获取cookie,例如

console.log(req.cookies.username);//Jack

  • 设置允许所有域访问
app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By",' 3.2.1');
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
  });

源代码index.js:

const express = require('express')
const app = express()
const bodyParser = require ('body-parser')
const cookieParser = require("cookie-parser")

app.use(
    bodyParser.urlencoded({
      extended: false,
    }),
  )
app.use(bodyParser.json())

//设置跨域访问
app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By",' 3.2.1');
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
  });

app.get('/', (req, res) =>{
    res.send('Hello World!')
})
app.get('/test', (req, res) =>{
  //get请求获取参数
  console.log(req.query)
  res.send({err:0,msg:"successfully"})
})

app.post("/user",(req,res)=>{
  //post请求获取参数
    console.log(req.body)
    
    res.send({err:0,data:arr})
})
app.listen(4000, () => console.log('Example app listening on port 4000!'))
相关标签: node.js