周凯,个人博客

  • 前端
  • 嵌入式
  • 工具
  • 后端
  • 随笔
个人记录
  1. 首页
  2. 前端
  3. javascript
  4. 正文

前端文件上传,解决跨域,nginx配置跨域

2023年 9月 22日 1396点热度 0人点赞 0条评论
  • 使用:post请求,xxx.com/proxyImg/proxyFile 文件名称是file

  • nginx配置

    location ^~ /proxyImg/ {
      add_header Access-Control-Allow-Origin *;
      add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
      # 注意 这里需要添加所有的header,不然前端还会报错提示header不允许, !!!注意根据错误添加
      add_header Access-Control-Allow-Headers 'accountid,uid,authorization,client';
      add_header 'Access-Control-Allow-Credentials' 'true';
    
      if ($request_method = 'OPTIONS') {
          return 204;
      } 
      client_max_body_size 20m;
      proxy_pass http://127.0.0.1:9595/;
      access_log /data/app/nginx/logs/proxyImg/access_log.log;
    }
  • nodejs代理代码

    • index.js
    const express = require('express');
    const app = express();
    //bodyParser不支持form-data
    const multipart = require('connect-multiparty');
    const multipartyMiddleware = multipart();
    const FormData = require('form-data');
    const Fs = require('fs');
    const fetch = require('node-fetch');
    const port = 9595
    
    app.post('/proxyFile*', multipartyMiddleware, function (req, res, next) {
        const ajaxHeaders = req.headers;
        const fields = req.body;
        const {uploadUrl} = req.body;
        const files = req.files;
        let form = new FormData();
        if (fields) {
            for (let i in fields) {
                if (fields.hasOwnProperty(i)) {
                    form.append(i, fields[i]);
                }
            }
        }
        if (files) {
            const item = files.file;
            form.append(item['fieldName'], Fs.createReadStream(item['path']));
        }
        //如果要指定请求头,要获取form对象的请求头,其他信息可以自定义
        let fileHeaders = form.getHeaders();
        fileHeaders['ticket'] = ajaxHeaders ['ticket'];
        fetch(uploadUrl, {
          method: 'POST',
          body: form,
          headers: fileHeaders,
        })
          .then((response) => response.json())
          .then((json) => res.json(json))
    });
    
    app.listen(port, function () {
        console.log("文件代理启动成功, 端口是: " + port)
    })
    • package.json
    {
      "name": "interface-proxy",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "dev": "nodemon index.js",
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "",
      "license": "ISC",
      "dependencies": {
        "connect-multiparty": "^2.2.0",
        "express": "^4.18.2",
        "form-data": "^4.0.0",
        "node-fetch": "2",
        "nodemon": "^3.0.1"
      }
    }
    • 启动:pm2 start index.js --name "文件代理服务-端口9595"

🎯 拓展阅读提示

本文涉及的内容已同步至公众号后台,我会在那里分享更多深度内容和实用技巧

→ 点击关注:一行梦境

公众号二维码
本作品采用 知识共享署名 4.0 国际许可协议 进行许可
标签: 暂无
最后更新:2023年 9月 22日

周凯

这个人很懒,什么都没留下

打赏 点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2022-现在 周凯,个人博客. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

蒙ICP备18004897号