标签:red app access 写法 场景 需要 配置 -o get
前后端分离场景后端需要配置跨域,否则浏览器那端跨域请求会报错。
跨域要配置的:
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‘ ) next() })
整体写法例子:
const express = require(‘express‘) const app = express() const port = 9000 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‘ ) next() }) app.get(‘/‘, (req, res) => { res.send(‘Hello World!‘) }) app.get(‘/mall/queryMall‘, (req, res) => { res.send({ code: 0, sum_num: 2, data: [ { id: 1, name: ‘商场一号‘, proportion: 10, address: ‘上海市,辖区,浦东新区‘, user: { id: 1, name: ‘zezhou一号‘, tc: ‘商品金额*一级提率‘, }, }, { id: 2, name: ‘商场二号‘, proportion: 5, address: ‘上海市,辖区,浦东新区‘, user: { id: 2, name: ‘zezhou二号‘, tc: ‘商品金额*一级提率‘, }, }, ], }) }) app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) })
标签:red app access 写法 场景 需要 配置 -o get
原文地址:https://www.cnblogs.com/zezhou/p/14666102.html