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

本文介绍如何在ExpressJS中配置基本的中间件,包括body-parser和cookie-parser的使用,以及如何设置跨域访问控制,使服务器能够响应来自不同域的请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需要安装的插件:

  • 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!'))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值