不确定为什么res.send不发送我的对象到前端

时间:2018-04-25 01:39:31

标签: javascript reactjs webpack jsx

所以我尝试了一切,但我无法弄清楚为什么tumblr对象没有通过res.send传递给我的前端。任何人都可以帮忙吗?我也试过res.json,但那并没有做任何事情。我收到了一个承诺错误,一个异常被捕,但我不确定为什么。我认为它与图像对象无法通过有关。



import React from 'react';
import axios from 'axios';

class SearchBar extends React.Component {
	 constructor(props) {
    super(props);
    this.state = {tag: "", images: ''};

  	this.handleChange = this.handleChange.bind(this);
  	this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event){
  	this.setState({tag: event.target.value});
  }

	handleSubmit(event) {
    event.preventDefault();
    const sendTag = () => (
			new Promise((resolve, reject) => {
	     axios.post('/tag', {
		  		tag: this.state.tag,
			  })
	     if(this.state.tag){
					resolve(console.log('in sendtag'))
				} else {
					reject (error)
				}
		}))
		.then(() => {
			 axios.post('/images')
			 .then(res => {
			 	console.log("AXIOS:", res)
			 		this.setState({images: res})
			 })
		})
		.then((res) => {
		  console.log('IMAGES:', this.state);
		})
    .catch((error) => {
	    console.log(error);
	  });

		sendTag()

  }

	render (){
		return (
			<div>
				<form onSubmit={this.handleSubmit}>
	          <input type="text" 
	          onChange={this.handleChange} 
	          className="searchTerm" 
						placeholder="Enter a tag" />
	        <input type="submit" value="Submit" />
	      </form>
				<div className="grid-container">

				</div>
			</div>
		)
	}
}

export default SearchBar;
&#13;
&#13;
&#13;

Server.js

&#13;
&#13;
//Express
const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
const port = process.env.PORT || 5000;

//TUMBLR I
const tumblr = require('tumblr.js');

//TOKENS
const secret = require('./secret/config.js');

//MIDDLEWARE
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, '../frontend/public')));

//INITIATE API
const client = tumblr.createClient({
	consumer_key: secret.consumer_key,
	consumer_secret: secret.consumer_secret,
	token: secret.token,
	token_secret: secret.token_secret
});

// API
new Promise(function(resolve, reject){
    app.post('/tag', (req, res) =>{
    	const tag = req.body.tag
    	if(tag){
					resolve(tag)
				} else {
					reject (error)
				}
			})
}).then(function(tag){
    return new Promise(function(resolve, reject){
    	console.log('TAG', tag)
    	console.log('tumble api')
      client.taggedPosts(tag, (error, data) => {
				if(data){
					console.log('data recieved')
					resolve(data)
				} else {
					reject (error)
					console.log('tumble api error')
				}
			})
    });
}).then(function(result){
    return new Promise(function(resolve, reject){
    	console.log('image to new variable')
    	const images = result
    	if (images){
    		resolve (images)
    	} else {
    		reject (error)
    	}
    })
}).then(function(images){
		console.log('send api')
   console.log('IMAGES', images)
			app.post('/images', (req, res) => {
				res.json(images)
			})
})

// FRONTEND ROUTE
app.get('/', (req, res) => {
	res.sendFile(path.join(__dirname, '../frontend/index.html'));
});

//SERVER
app.listen(port, () => console.log('Server running on localhost 5000!'));

module.exports = app;
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

我认为主要问题是您的res.json(images)调用是在app.post声明中,因此只有当客户在/images发出请求时才会触发。如果您删除app.post并在链的最后.then中调用res.json,它可能会起作用。但是,我不确定您的/tag路线是否设置正确。我没有看到任何承诺链或单独的/tag/image路由的原因,因为您进行的唯一异步呼叫是client.taggedPosts。因此,我建议您定义/tag路由,然后将所有逻辑放在该路由中,如下所示:

// API
app.post('/tag', function (req, res) {
    const tag = req.body.tag;
    if (!tag) {
        return res.send('please provide a tag');
    };
    console.log('TAG', tag)
    console.log('tumble api')
    client.taggedPosts(tag, function(error, data) {
        if(!data) {
            console.log('tumble api error');
            return res.send(error);
        }
        console.log('data recieved', data);
        console.log('image to new variable')
        const images = data;
        console.log('sending images');
        console.log('IMAGES', images);
        res.send(images);
    });
});

然后可以更新客户端上的handleSubmit()函数以使用/tag响应,如下所示:

handleSubmit (event) {
    event.preventDefault();
    function sendTag () {
        axios
            .post('/tag', { tag: this.state.tag })
            .then( function(images) {
                console.log("AXIOS response:", images)
                this.setState({images: images})
            })
            .then(function () {
                console.log('state:', this.state);
            })
            .catch(function(error) {
                console.log(error);
            });
    }
    sendTag();
}