我的React应用程序无法使用fetch API处理CORS ajax请求

时间:2016-11-28 23:54:43

标签: javascript ajax node.js mongodb reactjs

我正在慢慢地想要在我的react应用程序中使用node / mongo后端。我正在使用Create-React-App来实现一个带有后端的小型个人应用程序,该后端从Formsy提交值中获取信息,然后将其发布到数据库中。到目前为止,这是我的代码:

src/modules/mongo.js

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const ObjectId = require('mongodb').ObjectID;
const url = 'mongodb://localhost:27017/danielrubio';
const express = require('express');
const app = express();

app.listen(3001,function() {
 console.log('listening')
})

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});


app.post('http://localhost:3001/contact_submissions', (req, res, next) => {
  console.log(res);
})

这是我的src/modules/contact.js

import React, { Component } from 'react';
import Formsy from 'formsy-react';
import { FormsyText } from 'formsy-material-ui/lib';
import Paper from 'material-ui/Paper';
import RaisedButton from 'material-ui/RaisedButton';
import Snackbar from 'material-ui/Snackbar';
import '../assets/css/style.css';

class ContactForm extends Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.state = { open: false };
  }

  handleSubmit(data) {
    let formData = new FormData();
    formData.append("json", JSON.stringify(data));
    fetch('http://localhost:3001/contact_submissions', {
      method: 'POST',
      body: formData
    })
  }

  .......more code.....

根据Create react app github页面。这应该工作。好吧,至少它应该适用于console.log响应。但这不是正在发生的事情。相反我得到了这个错误contact.js:68 POST http://localhost:3001/contact_submissions 404 (Not Found)我不确定为什么会收到此错误。我已明确指定了我的快速路由,甚至将我的端口号硬编码到localhost上。应该没有理由找不到它。

我的第二种方法(再次来自create-react-app)是在package.json中添加"proxy": "http://localhost:3001"行。这是我收到的错误:

Fetch API cannot load http://localhost:3001/contact_submissions. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 404. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
contact:1 Uncaught (in promise) TypeError: Failed to fetch

create-react-app文档说我不应该在我的package.json中添加proxy行时出现此错误,但显然我遇到了问题。我在这里可以做错什么?

0 个答案:

没有答案