node express初学

index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

</head>

<body>
    <input type="text" class="search">
    <input type="button" value="Click" class="submit">
</body>
<script>
    var btn = document.querySelector('.submit');
    var input = document.querySelector('.search');

    btn.onclick = function () {
        console.log(input.value)
        fetch('http://localhost:8000/send', {
            method: 'POST',
            // mode: 'same-origin',
            mode: 'no-cors', //默认跨域 格式为"content-Type":"text/pain"
            body: "a=" + input.value + "&b=2&c=3",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            }
        }).then(res => {
            return res.json;
        }).then(data => {
            console.log(data);
        }).catch(err => console.log(err));
    }
    // 使用原始的
    // application / x - www - form - urlencoded,body需要是a = 1 & b=2 & c=3 格式,无法传递复杂多层次的对象

    // fetch('/test/post', {
    //     headers: {
    //         "Content-Type": "application/x-www-form-urlencoded"
    //     },
    //     method: 'POST',
    //     body: "a=1&b=2&c=3"
    // }) 
    // 通过使用application / json ,可以直接传递JSON字符串,post复杂类型

    // fetch('/test/post', {
    //     headers: {
    //         "Content-Type": "application/json"
    //     },
    //     method: 'POST',
    //     body: JSON.stringify({ a: 1, b: { c: 2, d: 3 } })
    // })

</script>

</html>

转载:https://blog.csdn.net/isaisai/article/details/78205376

app.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.listen(8000, function () {
    console.log('server running on port: 8000');
});

app.get('/index', function (req, res) {
    res.sendFile(__dirname + '/index.html');
});

app.post('/send', function (req, res) {
    console.log(req.body);
    res.send(req.body).end();
});

page.json

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.3",
    "express": "^4.16.4"
  }
}

设置允许所有域名跨域:

app.all("*",function(req,res,next){
    //设置允许跨域的域名,*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin","*");
    //允许的header类型
    res.header("Access-Control-Allow-Headers","content-type");
    //跨域允许的请求方式 
    res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == 'options')
        res.send(200);  //让options尝试请求快速结束
    else
        next();
}

设置允许指定域名“http://www.zhangpeiyue.com”跨域:

app.all("*",function(req,res,next){
    //设置允许跨域的域名,*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin","http://www.zhangpeiyue.com");
    //允许的header类型
    res.header("Access-Control-Allow-Headers","content-type");
    //跨域允许的请求方式 
    res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == 'options')
        res.send(200);  //让options尝试请求快速结束
    else
        next();
}

设置允许多个域名跨域:

app.all("*",function(req,res,next){
    if( req.headers.origin.toLowerCase() == "http://www.zhangpeiyue.com"
        || req.headers.origin.toLowerCase() =="http://127.0.0.1" ) {
        //设置允许跨域的域名,*代表允许任意域名跨域
        res.header("Access-Control-Allow-Origin", req.headers.origin);
    }
    //允许的header类型
    res.header("Access-Control-Allow-Headers", "content-type");
    //跨域允许的请求方式 
    res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == 'options')
        res.send(200);  //让options尝试请求快速结束
    else
        next();    
}

如果允许的域名较多,可以将允许跨域的域名放到数组当中:

app.all("*",function(req,res,next){
    var orginList=[
        "http://www.zhangpeiyue.com",
        "http://www.alibaba.com",
        "http://www.qq.com",
        "http://www.baidu.com"
    ]
    if(orginList.includes(req.headers.origin.toLowerCase())){
        //设置允许跨域的域名,*代表允许任意域名跨域
        res.header("Access-Control-Allow-Origin",req.headers.origin);
    }
    //允许的header类型
    res.header("Access-Control-Allow-Headers", "content-type");
    //跨域允许的请求方式
    res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == 'options')
        res.send(200);  //让options尝试请求快速结束
    else
        next();
}

————————————————
版权声明:本文为CSDN博主「张培跃吧」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u012149969/article/details/81145144

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

web修理工

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值