React开发中的跨域和Fetch的封装

787 阅读1分钟

跨域问题和Fetch

解决React开发中的跨域问题

第一种:在package.json 中 加上配置

在 脚手架创建的package.json中加上这个配置,就可以解决开发中的跨域问题

{
  "proxy":"http://tingapi.ting.baidu.com"
}

第二种:手动配置跨域

  1. 安装插件
$ npm install http-proxy-middleware --save
$ # or
$ yarn add http-proxy-middleware
  1. 在src目录下新建一个叫setupProxy.js的文件

setupProxy.js:

const proxy = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/api',  //用 /api来替代http://localhost:5000,所以以后的接口地址前面加/api就可以替代http://localhost:5000这个地址了
    proxy({
      target: 'http://localhost:5000',  //地址
      changeOrigin: true,
    })
  );
};

封装Fetch请求

文件夹路径:

utils

-- base.js -- http.js -- index.js

封装:

http.js:

import qs from 'querystring'  //引入nodejs提供的querystring 来处理

export const httpGet = (url) =>{
  const result = fetch(url)
  return result
}

export const httpPost = (url,params) =>{
  const result = fetch(url,{
    method:'POST',
    headers:{
      'Content-Type': 'application/x-www-form-urlencoded',
      "Accept":"application/json,text/plain,*/*"
    },
    body:qs.stringify(params)  //传入的params是一个对象,但是fetch要的是一个字符串,所以可以使用原生nodejs提供的querystring.stringify来把对象变成字符串
  })
  return result
}

base.js:

const base = {
  ownUrl:"http://www.baidu.com",  //配置接口路径
  indexUrl:"?tn=98012088_5_dg&ch=12"  //要拼接的路径
}

export default base

index.js:

import { httpGet, httpPost } from './http'
import base from './base'


export const getBaiduIndex = () => {   //get请求
  return httpGet(base.ownUrl + base.indexUrl)
}


export const postBaiduIndex = (params) =>{ //post请求
  return httpPost(base.ownUrl+base.login,params)
}

组件使用:

import React, { Component } from 'react';
import {getBaiduIndex,postBaiduIndex} from './utils/index' //导入
class FetchDemo extends Component {

  componentDidMount() {
    getBaiduIndex().then(res=>res.json()).then(data => {  //发送请求
      console.log(data)
    })
    postBaiduIndex({name:'xiaohong',age:22}).then(res=>res.json()).then(data => {
      console.log(data)
    })
  }

  render() {
    return (
      <div>
        fetchdemo
      </div>
    )

  }
}


export default FetchDemo