【问题标题】:unsure why res.send not sending my object to the front end不确定为什么 res.send 不将我的对象发送到前端
【发布时间】:2018-10-05 08:58:27
【问题描述】:

所以我已经尝试了所有方法,但我无法弄清楚为什么 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;

服务器.js

//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;

【问题讨论】:

  • 日志打印是否正确?您是否尝试过使用邮递员等其他客户端工具验证 REST API?
  • process.on('unhandledRejection', function onError(err) {console.error(err);});把它放在你的代码中,尝试运行应用程序,它会显示错误...
  • 所以,我添加了代码,现在数据显示在 post 对象中,但事实并非如此。谢谢你给我一个起点!
  • 抱歉没能找到您...您的意思是图像正在打印在日志上或在休息响应中。 ?
  • 所以现在当我从我的 ajax 控制台记录结果时,图像显示在我前端的对象中。数据以前不存在,但现在出现了。

标签: javascript reactjs webpack jsx


【解决方案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();
}

【讨论】:

  • 谢谢。问题是,我将标签发送到我的服务器,因此我可以将它与 tumblr 的 api 一起使用,然后将该数据发送回客户端。到目前为止,标签和 tumblr api 工作,但由于某种原因,我无法将数据从 api 发送回前端
  • 当您说您无法将数据从 teh api 发送回前端时,在您的逻辑中应用程序在信息未正确发送之前到达哪里?您是否在服务器端访问console.log('IMAGES', images)?如果是这样,是console.log("AXIOS:", res) 没有看到预期的res 数据吗?
  • 是的,我无法访问 console.log("AXIOS:", res)。我收到两个错误:POST localhost:5000/posts 404 (Not Found) & Uncaught (in promise) Error: Request failed with status code 404.
  • 好的,我仍然认为问题与定义 /images 路由的位置有关,我仍然没有看到任何理由定义 images 路由,因为你有数据你想要的实际上是由/tag 路由检索的。如果您真的想使用/images 路由,则需要单独定义它并在 post 调用中将信息传递给它,以便它知道要获取哪些图像。相反,我会更新前端以处理来自标签路由的数据,因为这是您进行 tumlr 调用的地方。我已经更新了我的答案,以说明我建议您如何简化客户端组件。
猜你喜欢
  • 2014-07-08
  • 2021-06-20
  • 2014-08-20
  • 1970-01-01
  • 2019-01-15
  • 2021-05-25
  • 2023-03-13
  • 2010-10-06
  • 1970-01-01
相关资源
最近更新 更多