react 脚手架环境设置代理服务器解决跨域

除了在nodejs里面的路由请求中设置外
	res.set('Access-Control-Allow-Origin', '*');
	
对于使用creat-react-app构建的项目
	1、npm run eject
		将当前位置抛出,让我们可以修改配置文件
		
	2、在package.json中添加
		"proxy":"http://localhost:后台服务器名称"
	
	3、将网络请求的路径修改
		去掉http://120.0.0.1; 直接写nodejs中的路由名

代码示例:
package.json文件:

  "proxy":"http://localhost:3000"

网络请求文件:

import React ,{Component}from 'react';
import User from './user'

class App extends React.Component {

  constructor()
  {
    super();

  }
  componentDidMount()
  {
    var flag=true;
    if(flag)
    {
      fetch('/news')
      .then(data=>{return data.json()})
      .then(res=>{console.log(res)})
    }else{

      fetch('/movie',{
        method:'POST',
        headers:{
        'Accept': 'application/json, text/plain, */*',
        'Content-Type': 'application/x-www-form-urlencoded'
        },
        body:"id=jeff"

      }).then(data=>{return data.json()})
      .then(res=>{console.log(res)})
    }
  }


  render(){
     
      return (
            <div className="App">
            <User />
          </div>
      );
  }
}

export default App;

nodejs文件:

var express=require('express');
var bodyParser = require('body-parser');
var app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
//创建服务器
var app=express();


//开启服务器并监听端口
app.listen(3000,function(){
    console.log('this express server is running at http://127.0.0.1:3000 ');

})

app.get('/', function (req, res, next) {
    

});

app.get('/news', function (req, res, next) {
    // res.set('Access-Control-Allow-Origin', '*');


    var news = {
        id: 1,
        title: 'news title1...',
        content: 'news content1...',
        commentsUrl: '/comments?newsId='
    };
    res.json(news);

});

app.post('/movie',urlencodedParser, function (req, res, next) {
    // res.set('Access-Control-Allow-Origin', '*');
    var id=req.body.id;


    var news = {
        id: id,
        title: 'news title1...',
        content: 'news content1...',
        commentsUrl: '/comments?newsId='
    };
    res.json(news);

});



module.exports=app;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值