zoukankan      html  css  js  c++  java
  • express配置跨域

    前后端分离场景后端需要配置跨域,否则浏览器那端跨域请求会报错。

    跨域要配置的:

    app.all('*', (req, res, next) => {
      // google需要配置,否则报错cors error
      res.setHeader('Access-Control-Allow-Credentials', 'true')
      // 允许的地址,http://127.0.0.1:9000这样的格式
      res.setHeader('Access-Control-Allow-Origin', req.get('Origin'))
      // 允许跨域请求的方法
      res.setHeader(
        'Access-Control-Allow-Methods',
        'POST, GET, OPTIONS, DELETE, PUT'
      )
      // 允许跨域请求header携带哪些东西
      res.header(
        'Access-Control-Allow-Headers',
        'Origin, X-Requested-With, Content-Type, Accept, If-Modified-Since'
      )
      next()
    })
    

      

      

    整体写法例子:

    const express = require('express')
    const app = express()
    const port = 9000
    
    let mall_data = require('./data/mall')
    
    app.all('*', (req, res, next) => {
      // google需要配置,否则报错cors error
      res.setHeader('Access-Control-Allow-Credentials', 'true')
      // 允许的地址,http://127.0.0.1:9000这样的格式
      res.setHeader('Access-Control-Allow-Origin', req.get('Origin'))
      // 允许跨域请求的方法
      res.setHeader(
        'Access-Control-Allow-Methods',
        'POST, GET, OPTIONS, DELETE, PUT'
      )
      // 允许跨域请求header携带哪些东西
      res.header(
        'Access-Control-Allow-Headers',
        'Origin, X-Requested-With, Content-Type, Accept, If-Modified-Since'
      )
      next()
    })
    
    app.post('/mall/createMall', (req, res) => {
      res.send({
        code: 0,
        msg: '创建成功!',
      })
    })
    
    app.get('/mall/queryMall', (req, res) => {
      res.send({
        code: 0,
        sum_count: mall_data.mall.length,
        data: mall_data.mall,
      })
    })
    
    app.get('/mall/getMallList', (req, res) => {
      let mallId = req.query.mallId
      let data = {}
      for (let item of mall_data.mall) {
        if (item.id == mallId) {
          data = item
          break
        }
      }
      res.send({
        code: 0,
        data: data,
      })
    })
    
    app.listen(port, () => {
      console.log(`Example app listening at http://localhost:${port}`)
    })
    

      

  • 相关阅读:
    Core Animation Programming Guide
    Core Animation Programming Guide
    Core Animation Programming Guide
    Core Animation Programming Guide
    Core Animation Programming Guide
    Core Animation Programming Guide
    UIScrollView_滚动视图
    Core Animation之基础介绍
    CORE ANIMATION的学习备忘录
    UIWindow & UIWindowLevel笔记
  • 原文地址:https://www.cnblogs.com/zezhou/p/14666102.html
Copyright © 2011-2022 走看看